This is a plugin to create request handlers with class-, method- & parameter-decorators. Those, can than be bound/mounted to an arbitrary router instance.
Table of Contents
npm install @routup/decorators --save
The following TypeScript options must be present in the project tsconfig.json file:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
To read the docs, visit https://routup.net
The first step is to define a Controller.
controller.ts
import {
DBody,
DController,
DDelete,
DGet,
DNext,
DParam,
DPost,
DRequest,
DResponse,
} from '@routup/decorators';
import {
Next,
Request,
Response,
send,
} from 'routup';
@DController('/users')
export class UserController {
@DGet('')
async getMany(
@DRequest() req: Request,
@DResponse() res: Response,
@DNext() next: Next
) {
return 'Hello, World!';
}
@DGet('/:id')
async getOne(
@DRequest() req: Request,
@DResponse() res: Response,
@DParam('id') id: string,
) {
return 'Hello, World!';
}
@DPost('')
async create(
@DRequest() req: Request,
@DResponse() res: Response,
@DBody() body: any,
) {
return 'Hello, World!';
}
@DDelete('/:id', [])
async delete(
@DRequest() req: Request,
@DResponse() res: Response,
@DParam('id') id: string,
) {
return 'Hello, World!';
}
}
The last step is to install the plugin and mount the controllers to a router instance.
Parameters like body, cookie and query cannot be automatically injected into the controller methods. Therefore, so-called parameter getters must be defined, with the help of which the parameters are extracted from the request object. If you do not use the corresponding decorator, they do not need to be provided.
app.ts
import { createServer } from 'node:http';
import { decorators } from '@routup/decorators';
import {
basic,
useRequestBody,
useRequestCookie,
useRequestCookies,
useRequestQuery,
} from '@routup/basic';
import { createNodeDispatcher, Router } from 'routup';
import { UserController } from './controller';
const router = new Router();
router.use(basic());
router.use(decorators({
controllers: [
UserController
],
parameter: {
body: (context, name) => {
if (name) {
return useRequestBody(context.request, name);
}
return useRequestBody(context.request);
},
cookie: (context, name) => {
if (name) {
return useRequestCookie(context.request, name);
}
return useRequestCookies(context.request);
},
query: (context, name) => {
if (name) {
return useRequestQuery(context.request, name);
}
return useRequestQuery(context.request);
},
},
}))
const server = createServer(createNodeDispatcher(router));
server.listen(3000);
Made with 💚
Published under MIT License.