@555platform/express-decorators 中文文档教程

发布于 3年前 浏览 20 更新于 3年前

Build

express-decorators

用于 Express.js 的轻型 Typescript 装饰器库,为常见模式提供快捷方式。

受以下项目的启发:

  • https://tsed.io/
  • https://github.com/StephenGrider/typescriptcasts/tree/master/server

Installation

您可以使用 npm 获取最新版本:

\$ npm install --save @555platform/express-decorators

Quick Start

您可以通过扩展 AppServer 类来创建 Web 服务器。

import {
  json,
  Settings,
  AppServer
} from '@555platform/express-decorators';

@Settings({ port: 5001 })
class TestServer extends AppServer {
  beforeGlobalRouteInit(): void {
    this.use(json());
  }

  onServerListens(port: number): void {
    console.log(`Test server running on port: ${port}`);
  }
}

AppServer 有几个生命周期方法可以被覆盖以执行自定义初始化。

beforeServerInit

此方法在 Web 服务器初始化之前自动调用。 它可用于执行任何必须在 Web 服务器启动之前运行的代码。

beforeGlobalRouteInit

此方法在 Web 服务器初始化之后但在创建路由之前执行。 它旨在自定义设置全局路由中间件或在定义路由之前执行其他活动。

onServerListens

Web 服务器启动后调用此方法。

Create Controller

@Controller('/')
class SimpleRoutes {
  @Get('/api')
  getApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Delete('/api')
  deleteApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Post('/api')
  postApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Put('/api')
  putApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Patch('/api')
  patchApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
      return;
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
      return;
    }
    res.send('Ok');
  }

  @Get('/params/:id')
  idApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id });
  }

  @Post('/multi/id/:id/message/:message')
  multiApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id || !req.params.message) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id, message: req.params.message });
  }
}

Create WebSocket Server Controller

您可以创建一个或多个 WebSocket 服务器,只要它们指向不同的路径即可。

WssBeginConnect 和 WssEndConnect 是将在 wss.on 连接函数执行开始和结束时由 express-decorators 调用的函数。

使用@Server decorated 的函数将在实例化新服务器时接收 WebSocket.Server 对象。

@WebSocketServer('/'), { enableKeepAlive: true }
class SocketGateway {
  @Authenticate
  authenticationHandler(req: Request, cb: AuthenticationCallback) {
    console.log('Authing...');
    const queryData = url.parse(req.url, true).query;

    if (queryData.access_token === 'somevalue') {
      cb(undefined, { id: 'someid' });
      return;
    }

    cb(new Error('Unauthorized'));
  }

  @WssBeginConnect
  beginConnectionHandler() {
    console.log('Begin connection');
  }

  @WssEndConnect
  endConnectionHandler() {
    console.log('End connection');
  }

  @WsOnPong
  pongHandler(ws: ExtWebSocket) {
    return function() {
      console.log('Received PONG');
      ws.isAlive = true;
    };
  }

  @WsOnMessage
  messageHandler(ws: ExtWebSocket) {
    return function(msg: string) {
      ws.send(msg);
    };
  }

  @WsOnOpen
  openHandler(ws: ExtWebSocket) {
    return function() {
      console.log('connected');
      ws.send(Date.now());
    };
  }

  @WsOnClose
  closeHandler(ws: ExtWebSocket) {
    return function() {};
  }

  @WsOnError
  errorHandler() {
    return function(error: Error) {
      console.log(`Error: ${error}`);
    };
  }

  @Server
  serverHandler(wss: WebSocket.Server) {
    console.log('serverHandler');
  }
}

Connect to Mongo via Mongoose

您可以通过 mongoose 属性将 Mongo 连接信息简单地传递给 AppServer 的设置:

@Settings({
        port: 5001,
        mongoose: {
          databaseURI: 'localhost',
          databaseName: 'mydb',
          dbUser: '',
          dbPassword: '',
          databaseReplSet: ''
        }
      })
      class TestServer extends AppServer {
        beforeGlobalRouteInit(): void {
          this.use(json());
        }

        onServerListens(port: number): void {
          console.log(`Test server running on port: ${port}`);
        }

        onMongooseConnected(): void {
          connectSuccess();
        }

        onMongooseError(error: Error): void {
          connectFailed();
        }
      }

Build

express-decorators

Lightweight Typescript decorator library for Express.js to provide shortcuts for common patterns.

Inspired by the following projects:

  • https://tsed.io/
  • https://github.com/StephenGrider/typescriptcasts/tree/master/server

Installation

You can get the latest release using npm:

\$ npm install --save @555platform/express-decorators

Quick Start

You can create web server by extending AppServer class.

import {
  json,
  Settings,
  AppServer
} from '@555platform/express-decorators';

@Settings({ port: 5001 })
class TestServer extends AppServer {
  beforeGlobalRouteInit(): void {
    this.use(json());
  }

  onServerListens(port: number): void {
    console.log(`Test server running on port: ${port}`);
  }
}

AppServer has couple life cycle methods that can be overwritten to perform custom initializations.

beforeServerInit

This method is automatically called before web server is initialized. It can be used to execute any code that must run before web server starts.

beforeGlobalRouteInit

This method is executed after web server is initialized but before routes are created. It is meant to be customized to set up global route midleware or perform other activities before routes are defined.

onServerListens

This method is called after web server starts.

Create Controller

@Controller('/')
class SimpleRoutes {
  @Get('/api')
  getApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Delete('/api')
  deleteApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Post('/api')
  postApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Put('/api')
  putApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Patch('/api')
  patchApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
      return;
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
      return;
    }
    res.send('Ok');
  }

  @Get('/params/:id')
  idApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id });
  }

  @Post('/multi/id/:id/message/:message')
  multiApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id || !req.params.message) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id, message: req.params.message });
  }
}

Create WebSocket Server Controller

You can create one or more WebSocket servers as long as they are pointing to different path.

WssBeginConnect and WssEndConnect are functions that will be called by express-decorators at the begining and end of execution of wss.on connection function.

Function deecorated with @Server will receive WebSocket.Server object when the new server is instantiated.

@WebSocketServer('/'), { enableKeepAlive: true }
class SocketGateway {
  @Authenticate
  authenticationHandler(req: Request, cb: AuthenticationCallback) {
    console.log('Authing...');
    const queryData = url.parse(req.url, true).query;

    if (queryData.access_token === 'somevalue') {
      cb(undefined, { id: 'someid' });
      return;
    }

    cb(new Error('Unauthorized'));
  }

  @WssBeginConnect
  beginConnectionHandler() {
    console.log('Begin connection');
  }

  @WssEndConnect
  endConnectionHandler() {
    console.log('End connection');
  }

  @WsOnPong
  pongHandler(ws: ExtWebSocket) {
    return function() {
      console.log('Received PONG');
      ws.isAlive = true;
    };
  }

  @WsOnMessage
  messageHandler(ws: ExtWebSocket) {
    return function(msg: string) {
      ws.send(msg);
    };
  }

  @WsOnOpen
  openHandler(ws: ExtWebSocket) {
    return function() {
      console.log('connected');
      ws.send(Date.now());
    };
  }

  @WsOnClose
  closeHandler(ws: ExtWebSocket) {
    return function() {};
  }

  @WsOnError
  errorHandler() {
    return function(error: Error) {
      console.log(`Error: ${error}`);
    };
  }

  @Server
  serverHandler(wss: WebSocket.Server) {
    console.log('serverHandler');
  }
}

Connect to Mongo via Mongoose

You can simply pass Mongo connection information to Settings for AppServer via mongoose property:

@Settings({
        port: 5001,
        mongoose: {
          databaseURI: 'localhost',
          databaseName: 'mydb',
          dbUser: '',
          dbPassword: '',
          databaseReplSet: ''
        }
      })
      class TestServer extends AppServer {
        beforeGlobalRouteInit(): void {
          this.use(json());
        }

        onServerListens(port: number): void {
          console.log(`Test server running on port: ${port}`);
        }

        onMongooseConnected(): void {
          connectSuccess();
        }

        onMongooseError(error: Error): void {
          connectFailed();
        }
      }
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文