使用overnightjs typescript 注解开发expressjs 应用
overnightjs 提供了基于注解的expressjs应用开发,包含了比较全的express 开发支持,使用简单,以下是一个简单的试用
项目准备
项目使用pkg 进行了打包处理
- 初始化
yarn init -y
- 添加依赖
yarn add @overnightjs/core @overnightjs/logger express http-status-codes
yarn add @types/express pkg typescript --dev
- pacakge.json 文件
添加了npm script 以及pkg 打包的配置
{
"name": "ts-express-decrator",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "node dist/index.js",
"live": "tsc -w",
"package": "pkg --options expose-gc -d ."
},
"bin": "dist/index.js",
"pkg": {
"scripts": "dist/**/*.js"
},
"dependencies": {
"@overnightjs/core": "^1.6.8",
"@overnightjs/logger": "^1.1.8",
"express": "^4.17.1",
"http-status-codes": "^1.3.2"
},
"devDependencies": {
"@types/express": "^4.17.1",
"pkg": "^4.4.0",
"typescript": "^3.6.3"
}
}
- typescript config
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"removeComments": true,
"strict": true,
"rootDirs": [],
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
代码编写
- 代码结构
src
├── SampleServer.ts
├── UserController.ts
└── index.ts
- 代码说明
index.ts 为应用的入口,SampleServer.ts 为 express server 的定义,UserController.ts 是一个rest 服务的定义
SampleServer.ts 代码:
import * as bodyParser from 'body-parser';
import { Server } from '@overnightjs/core';
import { Logger } from '@overnightjs/logger';
import { UserController } from './UserController';
export class SampleServer extends Server {
constructor() {
super(process.env.NODE_ENV === 'development'); // setting showLogs to true
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({extended: true}));
this.setupControllers();
}
private setupControllers(): void {
const userController = new UserController();
// super.addControllers() must be called, and can be passed a single controller or an array of
// controllers. Optional router object can also be passed as second argument.
super.addControllers([userController]/*, optional router here*/);
}
public start(port: number): void {
this.app.listen(port, () => {
Logger.Imp('Server listening on port: ' + port);
})
}
}
UserController.ts:
import { OK } from 'http-status-codes';
import { Controller, Get, Post } from '@overnightjs/core';
import { Logger } from '@overnightjs/logger';
import { Request, Response } from 'express';
@Controller('user/say-hello')
export class UserController {
@Get()
private get(req: Request, res: Response): any {
Logger.Info('get called');
return res.status(OK).json({
message: 'get_called',
});
}
@Post()
private post(req: Request, res: Response): any {
Logger.Info('post called');
return res.status(OK).json({
message: 'post_called',
});
}
}
- index.ts
import { SampleServer } from "./SampleServer";
let myServer = new SampleServer()
myServer.start(3000)
构建&&启动
- 构建
yarn live
- 打包
yarn packagee
- 运行打包的应用
mac 系统,当然打包是跨平台的
./ts-express-decrator-macos
[2019-10-08T07:01:21.168Z]: Server listening on port: 3000
- 访问效果
curl -i http://localhost:3000/user/say-hello
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 24
ETag: W/"18-aJruZ7f86jURaNXHzg+3fDFbLjs"
Date: Tue, 08 Oct 2019 07:02:02 GMT
Connection: keep-alive
{"message":"get_called"}%
说明
使用overnightjs 开发express 应用还是很方便的,当然 routing-controllers 也是一个不错的选择(更新还很频繁),而且typestack 团队开发
的好多typescript 的框架也是很好用的。
参考资料
https://github.com/seanpmaxwell/overnight
https://github.com/typestack/routing-controllers