1.0.3 • Published 1 year ago

simple-decor v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

simple-decor

Purpose

Modern REST API frameworks allow simple syntax to register new routes and type check their data transfer object (DTO). In express, these processes can be verbose, but migrating to newer frameworks is not always an option.

The goal of simple-decor is to bring in uncomplicated decorator-based route registration and DTO type checking to Express projects. Additionally, it plans to include automatic OpenAPI documentation generation in upcoming versions.

Installation

Using npm:

$ npm i simple-decor

Usage

Register a POST company/:companyId/user and DTO type checking using controller decorators

import { Post, ParamIsInt, BodyIsClass } from "simple-decor";

class UserController {
  @Post("company/:companyId/user")
  @ParamIsInt("companyId")
  @BodyIsClass(PostUserBody)
  post(req: Request, res: Response) {
    const { email, name } = req.body as PostUserBody;

    //create user ...

    res.send(200);
  }
}

Add registered routes to express application

import { setup } from "simple-decor";

const app = express();
app.listen(3000);
setup(app);

Decorators

Route registration

DecoratorParametersDescription
Getpath stringRegisters a new GET route
Patchpath stringRegisters a new PATCH route
Postpath stringRegisters a new POSTroute
Putpath stringRegisters a new PUT route
Deletepath stringRegisters a new DELETE route

Path param type checking

DecoratorParametersDescription
ParamExistsname:stringThrows error if http request does not contains a path parameter with given name
ParamIsIntname:stringThrows error if http request does not contains a path parameter with given name that contains only digits
ParamIsEmailname:stringThrows error if http request does not contains a path parameter with given name that loosely matches an email
ParamIsEnumname:string, enum:enumThrows error if http request does not contains a path parameter with given name that is in the given enum

Query param type checking

DecoratorParametersDescription
QueryExistsname:stringThrows error if http request does not contains a query parameter with given name
QueryIsIntname:stringThrows error if http request does not contains a query parameter with given name that contains only digits
QueryIsEmailname:stringThrows error if http request does not contains a query parameter with given name that loosely matches an email
QueryIsEnumname:string, enum:enumThrows error if http request does not contains a query parameter with given name that is in the given enum

Body type checking

DecoratorParametersDescription
BodyIsClassbodyClass: classThrows error if http reqest body does not match the given class (class must be annotated with class-validator and class-transformer decorators