NestJs Concise Tutorial

Keywords: node.js socket PHP TypeScript Java

After looking at koa,express and their derivative frameworks, it seems that NodeJs'Web development framework can not jump out of a fixed pattern. This question also bothers PHP. Is it possible to simplify development through annotations?
In fact, PHP has "annotations", but it is implemented by reading annotations through reflection, which is very low-level.
Today we're going to talk about a landmark NodeJs Web framework nestjs

Sample code

Before introducing nestjs, let's take a look at the example code of nestjs.

  1. HTTP interface
@Controller('socket')
@UseGuards(AdminGuard)
export class SocketController {
  private logger: Logger = new Logger(SocketController.name);

  constructor(private readonly gateway: SocketGateway,
              private readonly salesmanService: SalesmanService,
              private readonly hashidService: HashidService) {
  }

  @Post('interaction')
  async send(@Query('salesman_id') salesmanId: number, @Query('user_id') userId: number, @Body('content') content: string) {
    if (!salesmanId || !userId || !content) {
      throw new BadRequestException('Bad Request');
    }
    const salesman = await this.salesmanService.findById(salesmanId);
    if (!salesman) {
      throw new NotFoundException('Sales does not exist');
    }
    const roomId = this.salesmanService.makeSyncRoomKey(salesman);
    this.gateway.namespace.to(roomId).emit(SocketEvent.OnInteraction, { user_id: this.hashidService.encode(userId), content });
    return { errmsg: 'ok', errcode: 0 };
  }
}
  1. Socket.IO
@UseFilters(new WsExceptionFilter())
@WebSocketGateway({ namespace: 'socket', adapter: adapter(appConfig.redis) })
export class SocketGateway implements OnGatewayInit<SocketIO.Namespace>, OnGatewayConnection<SocketIO.Socket> {
  private logger: Logger = new Logger(SocketGateway.name);
  @WebSocketServer() public readonly namespace: SocketIO.Namespace;
  public adapter: adapter.RedisAdapter;

  constructor(
    private readonly salesmanService: SalesmanService,
    private readonly corporationService: CorporationService,
    private readonly hashidService: HashidService,
    private readonly userService: UserService,
    private readonly roomService: RoomService,
    private readonly messageService: MessageService,
    private readonly readService: ReadService,
    private readonly memberService: MemberService,
  ) {
  }

  afterInit(server: SocketIO.Namespace): any {
    this.adapter = server.adapter as adapter.RedisAdapter;
    this.logger.log(`initialized ${server.name}`);
  }

  /**
   * Enter the chat room
   * @param {SocketIO.Socket} client
   * @returns {any}
   */
  async handleConnection(client: SocketIO.Socket): Promise<any> {
    const { user_id, token, corporation_id, sign } = qs.parse(url.parse(client.request.url).query) as {
      [name: string]: string;
    };
    if (!user_id && !token && !corporation_id && !sign) {
      client.disconnect(true);
      return;
    }
    const realUserId = this.hashidService.decode(user_id);
    await promisify(client.join.bind(client))(this.roomService.makePersonalRoomId(realUserId)),
      client.emit(SocketEvent.Ready);
  }

  @SubscribeMessage(SocketEvent.Join)
  handleJoin(client: SocketIO.Socket, data: any) {
    if (JoinType.Chat === data.type) {
      return this.handleJoinChat(client, data);
    }
    if (JoinType.Sync === data.type) {
      return this.handleJoinSync(client, data);
    }
    client.disconnect(true);
  }

  @SubscribeMessage(SocketEvent.Leave)
  async handleLeave(client: SocketIO.Socket, data: any) {
    const { user_id, token, corporation_id, sign } = qs.parse(url.parse(client.request.url).query) as {
      [name: string]: string;
    };
    if (JoinType.Chat === data.type) {
      await promisify(client.leave.bind(client))(data.room_id);
      return { event: SocketEvent.Leave, data };
    }
    const isPersonal = user_id && token;
    const roomId = isPersonal
      ? await this.salesmanService.getRoomId(user_id, token)
      : await this.corporationService.getRoomId(corporation_id, sign);
    if (roomId) {
      await promisify(client.leave).bind(client)(roomId);
    }
    return { event: SocketEvent.Leave, data };
  }
// ...

Is it written like Java or Angular 4?

introduce

In fact, the architecture of nestjs originates from the spring framework of java, while the code organization borrows from the Module of Angular 4.

nestjs module architecture diagram

Start developing

  1. yarn global add @nestjs/cli
  2. nest new projectName
  3. cd projectName && yarn start

Written in the end

Because of the space relationship, the detailed documents of nestjs can be viewed on the official website. This article is just a framework introduction to open the door of the new world.

Posted by asy1mpo on Sun, 27 Jan 2019 09:51:14 -0800