@nfly/router
v1.2.0
Published
路由模块, 面向切面编程, 依赖注入的形式开发node服务
Downloads
5
Readme
Install
pnpm add @nfly/router
Usage
Register it if you need.
# Controller
import {
GET, Body, Service, Path, Query, Params, Before, After, Middleware,
} from '@nfly/router';
import { BaseController } from '@nfly/core';
import HomeService from '../../service/Home';
function Test(target: any, key: symbol|string, des: any) {
const old = des.value;
// eslint-disable-next-line no-param-reassign
des.value = async function (...args: any) {
console.log('func start');
await old.apply(this, args);
console.log('func end');
};
}
/**
* After Before用户装饰类 每个路由前或者后执行
*/
@Path('/user')
@After(async (ctx) => {
console.log('after each methods');
})
@Before(async (ctx) => {
console.log('before each methods');
// ctx.body = '没有权限';
// 如果return true; 会中断该下所有路由执行 否则正常执行
// return true;
})
@Middleware(async (ctx, next) => {
// class all methods use the middleware
await next();
})
class Home extends BaseController {
@Service(HomeService)
homeServer!: HomeService;
/**
* api path [/getUserInfo]
*/
@GET()
async getUserInfo() {
this.json({
code: 0,
message: '用户信息',
data: {
name: 'my name',
age: 100,
},
});
}
/**
* api path [/info]
*/
@GET('/info')
async renameUserInfo() {
this.json({
code: 0,
message: '自定义路由',
data: {
name: 'my rename',
age: 100,
},
});
}
/**
* api path [/:id]
*/
@Test
@Middleware(async (ctx, next) => {
console.log('this router use the middleware');
await next();
})
@GET('/last/:id')
async index(@Query('name') name: string, @Query() query: any, @Params('id') id: string) {
const list = await this.homeServer.getName();
this.success({
name,
id,
query,
list,
});
}
}
export default Home;
# Service
import { BaseService } from '@nfly/core';
import { Model } from '@nfly/orm';
import { Repository } from 'typeorm';
import { Photo } from '../../model/home';
class HomeService extends BaseService {
@Model<Photo>(Photo)
home!: Repository<Photo>;
async getName() {
const data = await this.home.find();
return data;
}
}
export default HomeService;
class Decorator
|Decorator|description| |-|-| |@Path(params: string)| class root path;| | @Middleware(params: Middleware) | koa middleware; | | @After(params: IContext) |on call after each method | | @before(params: IContext) |on call before each method |
method Decorator
|Decorator|description|other Decorators| |-|-|-| |@GET(params?: string)| router path;|@POST;@PUT;@DELETE;...| | @Middleware(params: Middleware) | koa middleware; || | @Query(args: string|string[]) | get fields from ctx |@Params;@Body;@Headers;@Cookies|
attribute Decorator
|Decorator|description| |-|-| |@Model| typeorm Model| | @Service | BaseService |