Inheritance is one of the four pillars of object-oriented programming. JavaScript has the prototype-based inheritance, and with it, one object can acquire properties of another object. Even though JavaScript has the class keyword, it still uses prototypes under the hood.
If you want to know to know more about prototypes, check out this article I wrote a few years ago.
In this article, we explain the mixin pattern in the context of TypeScript and provide examples of how we can use it with NestJS.
Creating mixins with TypeScript
Besides inheritance, JavaScript and TypeScript support another way of attaching methods and properties to classes. Following the TypeScript 2.2 RC announcement, the mixin as a function that:
- takes a constructor
- declares a class that extends that constructor
- adds members to that new class
- and returns the class itself.
The mixin pattern is also popular in languages such as Scala.
Let’s create a fundamental example of a mixin:
type Constructor = new ( ...args: any[] ) => {};
function Person<BaseType extends Constructor>(Base: BaseType) { return class extends Base { name: string; }; } |
The above Constructor type is provided in the official documentation and makes sure that what we pass to the Person function is a class.
In a nutshell, whatever class we pass to the Person function, it becomes a person.
const Teacher = Person( class { subject: string; } )
const John = new Teacher();
john.name = ‘John’; john.subject = ‘Math’; |
Constrained mixins
Above, we’ve created a Constructor type that doesn’t contain any information about the class we pass to the mixin. Sometimes, we would like the mixin to use some of the properties from the class it extends.
We can deal with the above problem by creating types that are more constrained.
type Constructor<Type = {}> = new ( ...args: any[] ) => Type;
type HasTheSubject = Constructor<{ subject: string }>; |
Thanks to creating the above types, we can define a mixin that uses the name property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function CanIntroduceSelf<BaseType extends HasTheSubject>(Base: BaseType) { return class extends Base { introduce() { console.log(`Hello, I teach ${this.subject}`); } }; }
const Teacher = CanIntroduceSelf( class { subject: string;
constructor(subject: string) { this.subject = subject; } } )
const mathTeacher = new Teacher(‘math’); mathTeacher.introduce(); // Hello, I teach math |
Multiple inheritance
Some programming languages implement multiple inheritance where a class can inherit from more than one parent class. Unfortunately, neither JavaScript nor TypeScript doesn’t include it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Day { day: number; month: number; year: number;
setDay(day: number, month: number, year: number) { this.day = day; this.month = month; this.year = year; } }
class Time { hour: number; minute: number; second: number;
setTime(hour: number, minute: number, second: number) { this.hour = hour; this.minute = minute; this.second = second; } }
class EventTakingPlace extends Day, Time { name: string; place: string; } |
error TS1174: Classes can only extend a single class.
We can use the mixin pattern to combine multiple classes. To do that, we first need to define the applyMixin function suggested in the official documentation:
function applyMixins(derivedConstructor: any, constructors: any) { constructors.forEach((baseConstructor) => { Object.getOwnPropertyNames(baseConstructor.prototype).forEach((name) => { Object.defineProperty( result, name, Object.getOwnPropertyDescriptor(baseConstructor.prototype, name) || Object.create(null) ); }); }); return derivedConstructor } |
I’ve made slight adjustments to the example from the documentation by writing more descriptive variable names and returning the derivedConstructor.
onst EventTakingPlace = applyMixins( class { name: string; place: string; constructor(name: string, place: string) { this.name = name; this.place = place; } }, [Day, Time] )
const johnMayerConcert = new EventTakingPlace(‘John Mayer concert’, ‘New York’);
johnMayerConcert.setDay(1, 3, 2022); johnMayerConcert.setTime(19, 30, 0); |
There is a significant drawback to using this approach, even though it is provided in the official documentation. Using the any type in the applyMixins function is a big disadvantage, and we should avoid using it as much as possible.
Instead, we can compose multiple mixins and achieve a similar result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
function Day<BaseType extends Constructor>(Base: BaseType) { return class extends Base { day: number; month: number; year: number;
setDay(day: number, month: number, year: number) { this.day = day; this.month = month; this.year = year; } } }
function Time<BaseType extends Constructor>(Base: BaseType) { return class extends Base { hour: number; minute: number; second: number;
setTime(hour: number, minute: number, second: number) { this.hour = hour; this.minute = minute; this.second = second; } } }
const EventTakingPlace = Day( Time( class { name: string; place: string; constructor(name: string, place: string) { this.name = name; this.place = place; } } ) ) |
Mixins with NestJS
There is a good chance that you don’t find mixins very appealing. When using NestJS, they can be pretty helpful, though.
Extending the existing mixins
A big part of it is that NestJS uses mixins under the hood. A good example is the FileInterceptor. If we ever want to extend its functionalities for any reason, we need to create our mixin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import { FileInterceptor } from ‘@nestjs/platform-express’; import { Injectable, mixin, NestInterceptor, Type } from ‘@nestjs/common’; import { ConfigService } from ‘@nestjs/config’; import { MulterOptions } from ‘@nestjs/platform-express/multer/interfaces/multer-options.interface’; import { diskStorage } from ‘multer’;
interface LocalFilesInterceptorOptions { fieldName: string; path?: string; fileFilter?: MulterOptions[‘fileFilter’]; limits?: MulterOptions[‘limits’]; }
function LocalFilesInterceptor (options: LocalFilesInterceptorOptions): Type<NestInterceptor> { @Injectable() class Interceptor implements NestInterceptor { fileInterceptor: NestInterceptor; constructor(configService: ConfigService) { const filesDestination = configService.get(‘UPLOADED_FILES_DESTINATION’);
const destination = `${filesDestination}${options.path}`
const multerOptions: MulterOptions = { storage: diskStorage({ destination }), fileFilter: options.fileFilter, limits: options.limits }
this.fileInterceptor = new (FileInterceptor(options.fieldName, multerOptions)); }
intercept(...args: Parameters<NestInterceptor[‘intercept’]>) { return this.fileInterceptor.intercept(...args); } } return mixin(Interceptor); }
export default LocalFilesInterceptor; |
The above code comes from API with NestJS #55. Uploading files to the server
There are a few essential things to notice above. First, we create our Interceptor class and return it using the mixin function from the @nestjs/common package. The mixin function applies the Injectable decorator under the hood.
Unfortunately, NestJS currently experiences an issue where not using @Injectable directly causes the reflect-metadata library not to pick it up. Because of that, not using @Injectable() at the top would cause the dependency injection to fail, and our configService would stay undefined. Hopefully, this bug will be resolved at some point.
Thanks to creating the above mixin, we can now easily use it in one of our controllers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Post(‘avatar’) @UseGuards(JwtAuthenticationGuard) @UseInterceptors(LocalFilesInterceptor({ fieldName: ‘file’, path: ‘/avatars’, fileFilter: (request, file, callback) => { if (!file.mimetype.includes(‘image’)) { return callback(new BadRequestException(‘Provide a valid image’), false); } callback(null, true); }, limits: { fileSize: Math.pow(1024, 2) // 1MB } })) async addAvatar(@Req() request: RequestWithUser, @UploadedFile() file: Express.Multer.File) { return this.usersService.addAvatar(request.user.id, { path: file.path, filename: file.originalname, mimetype: file.mimetype }); } |
Passing additional arguments
Sometimes, we would like to pass additional arguments to structures that don’t usually allow us to do that.
The official NestJS docs for authorization suggest creating separate @Roles() for setting a role and RolesGuard for checking them. Fortunately, we can solve that by creating a mixin that creates a custom guard with an additional argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import Role from ‘./role.enum’; import { CanActivate, ExecutionContext, mixin, Type } from ‘@nestjs/common’; import RequestWithUser from ‘../authentication/requestWithUser.interface’; import JwtAuthenticationGuard from ‘../authentication/jwt-authentication.guard’; const RoleGuard = (role: Role): Type<CanActivate> => { class RoleGuardMixin extends JwtAuthenticationGuard { async canActivate(context: ExecutionContext) { await super.canActivate(context); const request = context.switchToHttp().getRequest<RequestWithUser>(); const user = request.user; return user?.roles.includes(role); } } return mixin(RoleGuardMixin); } export default RoleGuard; |
You can find the above code in API with NestJS #56. Authorization with roles and claims
Using the above approach, we can pass arguments when using our RoleGuard. It wouldn’t be possible without using a mixin.
@Delete(‘:id’) @UseGuards(PermissionGuard(PostsPermission.DeletePost)) async deletePost(@Param(‘id’, ParseIntPipe) id: number) { return this.postsService.deletePost(id); } |
Summary
Most of the time, using mixins to extend our classes might not be a fitting option. Even though that’s the case, mixins have some uses when working with the NestJS framework. Since it uses them under the hood, we might need to create our mixins to extend them. Also, mixins can come in handy when we want to pass additional arguments to structures such as guards.
1 thought on “API with NestJS #57. Composing classes with the mixin pattern”