Nest.js Tutorial

Composing classes with the mixin pattern

Marcin Wanago
Uncategorized

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:

1type Constructor = new (
2  ...args: any[]
3) => {};
4 
5function Person<BaseType extends Constructor>(Base: BaseType) {
6  return class extends Base {
7    name: string;
8  };
9}
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.

1const Teacher = Person(
2  class {
3    subject: string;
4  }
5)
6 
7const John = new Teacher();
8 
9john.name = 'John';
10john.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.

1type Constructor<Type = {}> = new (
2  ...args: any[]
3) => Type;
4 
5type HasTheSubject = Constructor<{ subject: string }>;

Thanks to creating the above types, we can define a mixin that uses the name property.

1function CanIntroduceSelf<BaseType extends HasTheSubject>(Base: BaseType) {
2  return class extends Base {
3    introduce() {
4      console.log(`Hello, I teach ${this.subject}`);
5    }
6  };
7}
8 
9const Teacher = CanIntroduceSelf(
10  class {
11    subject: string;
12 
13    constructor(subject: string) {
14      this.subject = subject;
15    }
16  }
17)
18 
19const mathTeacher = new Teacher('math');
20mathTeacher.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.

1class Day {
2  day: number;
3  month: number;
4  year: number;
5 
6  setDay(day: number, month: number, year: number) {
7    this.day = day;
8    this.month = month;
9    this.year = year;
10  }
11}
12 
13class Time {
14  hour: number;
15  minute: number;
16  second: number;
17 
18  setTime(hour: number, minute: number, second: number) {
19    this.hour = hour;
20    this.minute = minute;
21    this.second = second;
22  }
23}
24 
25class EventTakingPlace extends Day, Time {
26  name: string;
27  place: string;
28}
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:

1function applyMixins(derivedConstructor: any, constructors: any) {
2  constructors.forEach((baseConstructor) => {
3    Object.getOwnPropertyNames(baseConstructor.prototype).forEach((name) => {
4      Object.defineProperty(
5        result,
6        name,
7        Object.getOwnPropertyDescriptor(baseConstructor.prototype, name) ||
8        Object.create(null)
9      );
10    });
11  });
12  return derivedConstructor
13}
I’ve made slight adjustments to the example from the documentation by writing more descriptive variable names and returning the derivedConstructor.
1onst EventTakingPlace = applyMixins(
2  class {
3    name: string;
4    place: string;
5    constructor(name: string, place: string) {
6      this.name = name;
7      this.place = place;
8    }
9  },
10  [Day, Time]
11)
12 
13const johnMayerConcert = new EventTakingPlace('John Mayer concert', 'New York');
14 
15johnMayerConcert.setDay(1, 3, 2022);
16johnMayerConcert.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.

1function Day<BaseType extends Constructor>(Base: BaseType) {
2  return class extends Base {
3    day: number;
4    month: number;
5    year: number;
6 
7    setDay(day: number, month: number, year: number) {
8      this.day = day;
9      this.month = month;
10      this.year = year;
11    }
12  }
13}
14 
15function Time<BaseType extends Constructor>(Base: BaseType) {
16  return class extends Base {
17    hour: number;
18    minute: number;
19    second: number;
20 
21    setTime(hour: number, minute: number, second: number) {
22      this.hour = hour;
23      this.minute = minute;
24      this.second = second;
25    }
26  }
27}
28 
29const EventTakingPlace = Day(
30  Time(
31    class {
32      name: string;
33      place: string;
34      constructor(name: string, place: string) {
35        this.name = name;
36        this.place = place;
37      }
38    }
39  )
40)

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.

1import { FileInterceptor } from '@nestjs/platform-express';
2import { Injectable, mixin, NestInterceptor, Type } from '@nestjs/common';
3import { ConfigService } from '@nestjs/config';
4import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
5import { diskStorage } from 'multer';
6 
7interface LocalFilesInterceptorOptions {
8  fieldName: string;
9  path?: string;
10  fileFilter?: MulterOptions['fileFilter'];
11  limits?: MulterOptions['limits'];
12}
13 
14function LocalFilesInterceptor (options: LocalFilesInterceptorOptions): Type<NestInterceptor> {
15  @Injectable()
16  class Interceptor implements NestInterceptor {
17    fileInterceptor: NestInterceptor;
18    constructor(configService: ConfigService) {
19      const filesDestination = configService.get('UPLOADED_FILES_DESTINATION');
20 
21      const destination = `${filesDestination}${options.path}`
22 
23      const multerOptions: MulterOptions = {
24        storage: diskStorage({
25          destination
26        }),
27        fileFilter: options.fileFilter,
28        limits: options.limits
29      }
30 
31      this.fileInterceptor = new (FileInterceptor(options.fieldName, multerOptions));
32    }
33 
34    intercept(...args: Parameters<NestInterceptor['intercept']>) {
35      return this.fileInterceptor.intercept(...args);
36    }
37  }
38  return mixin(Interceptor);
39}
40 
41export 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@Post('avatar')
2@UseGuards(JwtAuthenticationGuard)
3@UseInterceptors(LocalFilesInterceptor({
4  fieldName: 'file',
5  path: '/avatars',
6  fileFilter: (request, file, callback) => {
7    if (!file.mimetype.includes('image')) {
8      return callback(new BadRequestException('Provide a valid image'), false);
9    }
10    callback(null, true);
11  },
12  limits: {
13    fileSize: Math.pow(1024, 2) // 1MB
14  }
15}))
16async addAvatar(@Req() request: RequestWithUser, @UploadedFile() file: Express.Multer.File) {
17  return this.usersService.addAvatar(request.user.id, {
18    path: file.path,
19    filename: file.originalname,
20    mimetype: file.mimetype
21  });
22}

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.

1import Role from './role.enum';
2import { CanActivate, ExecutionContext, mixin, Type } from '@nestjs/common';
3import RequestWithUser from '../authentication/requestWithUser.interface';
4import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
5 
6const RoleGuard = (role: Role): Type<CanActivate> => {
7  class RoleGuardMixin extends JwtAuthenticationGuard {
8    async canActivate(context: ExecutionContext) {
9      await super.canActivate(context);
10 
11      const request = context.switchToHttp().getRequest<RequestWithUser>();
12      const user = request.user;
13 
14      return user?.roles.includes(role);
15    }
16  }
17 
18  return mixin(RoleGuardMixin);
19}
20 
21export 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.

1@Delete(':id')
2@UseGuards(PermissionGuard(PostsPermission.DeletePost))
3async deletePost(@Param('id', ParseIntPipe) id: number) {
4  return this.postsService.deletePost(id);
5}

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.