在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:zaaack/koa-dec-router开源软件地址:https://github.com/zaaack/koa-dec-router开源编程语言:JavaScript 100.0%开源软件介绍:koa-dec-router
Installnpm i koa-dec-router
or yarn add koa-dec-router Demoapp.js import Koa from 'koa'
import DecRouter from 'koa-dec-router'
const decRouter = DecRouter({
controllersDir: `${__dirname}/controllers`,
before: null, // global middleware
after: null, // global middleware
})
const app = new Koa()
// decRouter.router: `koa-router` instance
app.use(decRouter.router.routes())
app.use(decRouter.router.allowedMethods()) controllers/api.js import { controller, get, post } from 'dec-router'
async function apiHandler(ctx, next) {
console.log('handle all api and subclass\'s')
await next()
}
@controller('/api', apiHandler)
export default class Api {
async getApiCommon(ctx) {
// ...
return // some common data
}
} controllers/posts.js import { controller, get, post } from 'dec-router'
import Api from './api'
async function postHandler(ctx, next) {
console.log('handle post')
await next()
}
// define multi controller class in one file. You can passing {expose: false} to disable exposing this controller, which can still be inherit.
@controller('/subpost')
export class Subpost {
@get('s')
async list(ctx) {
ctx.body = 'get subpost'
}
}
@controller('/post')
export default class Post extends Api {
@get('s') // final path = parent controller path + controller path + method path
async list(ctx) {
const commonData = await super.getApiCommon()
ctx.body = 'get posts'
}
@get('/:id', {priority: -1}) // wildcard using low priority, let `special` method handle first
async get(ctx) {
ctx.body = 'get' + ctx.params.id
}
@get('/special')
async special(ctx) {
ctx.body = 'special post'
}
} Console outputTo output all routes generated by dec-router, you can run your app like DEBUG=dec-router,your-app:* node ./your-app.js For windows, using cross-env cross-env DEBUG=dec-router,your-app:* node ./your-app.js API ReferenceDecRouter(options)
@controller(path, opts, ...middlewares)
@route(method, path, opts, ...middlewares)
@get(path, opts, ..middlewares)alias of @route('get', path, opts, ...middlewares) @head(path, opts, ..middlewares)alias of @route('head', path, opts, ...middlewares) @post(path, opts, ..middlewares)alias of @route('post', path, opts, ...middlewares) @put(path, opts, ..middlewares)alias of @route('put', path, opts, ...middlewares) @del(path, opts, ..middlewares)alias of @route('delete', path, opts, ...middlewares) @patch(path, opts, ..middlewares)alias of @route('patch', path, opts, ...middlewares) @all(path, opts, ..middlewares)alias of @route('use', path, opts, ...middlewares) |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论