sahilrajput.com

learn-nestjs

REPOSITORY - https://github.com/sahilrajput03/learn-nestjs/


Source of below image - Click here

image

import * as path from 'node:path';
import * as url from 'node:url';
import * as fs from 'fs';
import * as os from 'os';

Scripts guide from official nestjs docs

Docs: Click here

image


How do we perform data-type conversions in params and query dto’s?

We can use Type decorator i.e, @Type from class-transformer.

From official docs:

image

image

Fixing circular-dependeny for nestjs - Awesome Article

NOTE: My current slasher backend project has a good docs guide in the project readme as well.

Official Guide from NestJs: Click here

Click here

Also, in slasher we can directly make user of models inside the controller’s instead of using an serviceMethod of a different service. But this is only feasible if the logic we already have been using a service method for has very simple logic which can be put in controller directly without bringing a lot of complexities to the controller code.

Versioning

OFFICIAL DOCS: Click here

RouterModule for adding a prefix to all paths of Controllers of a Module

OFFICIAL DOCS: Router module: Click here

Note: In below way the module’s controllers are accessible at the prefixed path only (no longer accessible without the prefixed path).

image

Above image from source, we need to learn that adding DashboardModule to the list of imports is necessary and also adding DashboardModule to the module property inside the RouterModule.register’s array.

global interceptors in nestjs:

Interceptors NestJs: Click here

Source: Click here

In file app.module.ts, you can add a suitable provider like that:

image

USAGE:

image

Interceptors can be nested in this way I guess:

image

interceptors in nestjs:

image

http requests, and jest mocking:

    it.only('cool testing', async () => {
      jest.spyOn(httpService, 'get')
      .mockImplementation(() => of({ data: 100, status: 202, statusText: '', headers: {}, config: {} }))
      .mockImplementationOnce(() => of({
        data: 101,
        status: 202,
        statusText: '',
        headers: {},
        config: {},
      }))
      .mockImplementationOnce(() => of({
        data: 102,
        status: 202,
        statusText: '',
        headers: {},
        config: {},
      }));

      const { data: data1 } = await lastValueFrom(httpService.get('/'));
      console.log({ data1 }); // 101

      const { data: data2 } = await lastValueFrom(httpService.get('/'));
      console.log({ data2 }); // 102

      const { data: data3 } = await lastValueFrom(httpService.get('/'));
      console.log({ data3 }); // 100

      const { data: data4 } = await lastValueFrom(httpService.get('/'));
      console.log({ data4 }); // 100
      expect(1).toBe(1);
    });

Other Cool things:

image

image

Swagger Usage