koa-ts-decorator-router
v0.1.8
Published
you can via typescript class decorator to define koa-routers.
Downloads
16
Maintainers
Readme
koa-ts-decorator-router
You can via typescript class and decorator to difine your koa-router's routes middleware for Koa.
Features
You can define your koa-router's routes by es6 class. like this
@Controller({
path: "user",
})
export class UserController {
login({ name }: User) {
console.log("param", name);
return name;
}
@Method({
path: "myRegister",
method: "POST",
})
async register({ name, pass }: User) {
const user = new User();
user.name = name;
user.pass = pass;
await mysql().getRepository(User).save(user);
return user;
}
}
This will be transfer to koa-route like:
const Router = require("@koa/router");
const router = new Router();
router.get("/user/login", async (ctx, next) => {
ctx.body = name; //name is abave class UserController login returned
await next();
});
router.post("/user/myRegister", async (ctx, next) => {
ctx.body = user;
await next();
});
Installation
# npm ..
npm i koa-ts-decorator-router
# yarn ..
yarn add koa-ts-decorator-router
API
ClassifyKoaRouter ⏏
Kind: Exported function
| Param | Type | Description | | ---------------- | ------------------- | ---------------------- | | [router] | Object | instance of koa-router | | [scanController] | Ojbect | scan controller config | | [otherOpts] | Ojbect | other config |
scanController Type
type ScanControllerOpts = {
dirname: string; // your Controller ts file dir
filter: RegExp; //filter you need regist to koa-router
};
otherOpts Type
type OtherOpts = {
convertDigital?: boolean; // is try convert param string to number.
assignQuery?: boolean; // is Object.assign ctx.request.query to ctx.request.body when body is Object type.
logRoute?: boolean; // console.log register route, while you debug app you can turn on this config.
/**
* if return ture, will be call method. else not call method and ctx.body will be set to you function return value.
* */
onBeforeCallMethod?: (
ctx: ParameterizedContext,
methodConf: {
fullPath: string;
method: MethodType;
customConf?: T;
},
) => unknown;
};
Controller Decorator ([controllerDecoratorOpts])
controllerDecoratorOpts Type
type ControllerDecoratorConf = {
path?: string;
};
- Notice: if you not offer path, while register koa-route will it default value will be
/
.
@Path(path:string)
this decorator can use for controller and method.
@GET(path?:string)
@POST(path?:string)
@PUT(path?:string)
@PATCH(path?:string)
@DELETE(path?:string)
@ALL(path?:string)
@CustomConf(customConf:T)
Controller Method Decorator ([methodDecoratorOpts])
type MethodDecoratorConf<T> = {
path?: string;
method?: MethodType;
customConf?: T;
rateLimitInstance?: RateLimiterStoreAbstract;
rateLimitConsumeFn?: {
(
rateLimitInstance: RateLimiterStoreAbstract,
ctx: Koa.ParameterizedContext,
): Promise<any>;
};
};
If you offer RateLimiterStoreAbstract, and rateLimitConsumeFn
you can define you function to consume rateLimit.
Controller 's path and Method's path composition to koa-route's path.
eg1
:
export class UserController {
login({ name }: User) {
console.log("param", name);
return name;
}
}
koa-route will be router.get(/login)
eg2
:
@Controller({
path: "user",
})
export class UserController {
login({ name }: User) {
console.log("param", name);
return name;
}
}
koa-route will be router.get(/user/login)
eg3
:
export class UserController {
@Method({
method: "POST",
})
login({ name }: User) {
console.log("param", name);
return name;
}
}
koa-route will be router.post(/login)
eg5
:
@Controller({
path: "////user//",
})
export class UserController {
@Method({
method: "POST",
path: "//login////",
})
login({ name }: User) {
console.log("param", name);
return name;
}
}
koa-route will be router.post(/user/login)
eg6
:
@Controller({
path: "user",
})
export class UserController {
@Method({
method: "POST",
path: "login/:id",
})
login({ name }: User) {
console.log("param", name);
return name;
}
}
koa-route will be router.post(/user/login/:id)
Controller Method Param
- request.body is
Array
, It will be calllogin(request.body, ctx.request, router)
- request.body is
Object
, And if otherOpt assignQuery is ture . It will be calllogin(Object.assign(request.body,request.query), ctx.request, router)
- If method
First param
isArray
orObject
, And if otherOpt convertDigital is true. we will try to auto recursion transform param value, convertstring
tonumber
orfloat
.
Example
Basic usage:
The directory structure
.
├── controllers
│ ├── FileController.ts
│ └── UserController.ts
├── index.ts
index.ts
import Koa from "koa";
import Router from "koa-router";
import KoaBody from "koa-body";
app.use(
KoaBody({
multipart: true,
}),
);
const router = new Router();
app.use(
ClassifyKoaRouter(router, {
dirname: path.join(__dirname + "./controllers"), // your Controller ts file dir
filter: /(.*Controller)\.ts$/, //filter you need regist to koa-router
}),
);
UserController.ts
@Controller({
path: "user",
})
export class UserController {
login({ name }: User) {
console.log("param", name);
return name;
}
@Method({
path: "myRegister",
method: "POST",
})
async register({ name, pass }: User) {
const user = new User();
user.name = name;
user.pass = pass;
await mysql().getRepository(User).save(user);
return user;
}
}
Upload usage:
FileController
@Controller({
path: "file",
})
export class FileController {
@Method({
method: "POST",
})
upload(params: any, { files }: { files: Files }) {
return saveFiles(files).map((i) => {
delete i.filePath;
return i;
});
}
}
Notice
Use this lib must be cooperation with koa-body and koa-router.
Because lib use typescript decorator, you need allow options at
tsconfig.json
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
Contributing
Please submit all issues and pull requests to the hxdyj/koa-ts-decorator-router repository!
Support
If you have any problem or suggestion please open an issue here.