0.2.71 • Published 2 years ago

express-dto v0.2.71

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Contributors Forks Stargazers Issues MIT License

About The Project

We use the Mongoose Model.validate() method for validation and the Mongoose Document.toJSON() method for filtering. If you have previous experience with Mongoose, this module will be a breeze for you :smile:

We are currently working on further development to enable automatic Swagger integration through DTO schemas.

  • Please note that this module can only be used with Express.

Built With

We express our gratitude to Mongoose for its excellent validation mechanism. We thank the UUID team for providing a simple and useful package.

Getting Started

This is an example of how you may give instructions on setting up your project locally. To get a local copy up and running follow these simple example steps.

Installation

npm install express-dto
yarn add express-dto

Usage

You can utilize this module in two different ways. Examples are provided for both methods.

  • The Express-dto module is only applicable to the "POST," "PUT," "PATCH," "GET," and "DELETE" HTTP methods.

Method 1

Using Router methods encapsulating Express methods.

import express, { Router } from "express";
import { Inject } from "express-dto";

// Your DTO files
import { GetUserDto, UpdateUserDto, AddUserDto } from "./dtos";
import CreateAddressDto from "./createAddress.dto.ts";
import DeleteAddressDto from "./deleteAddress.dto.json";

Injection process

const options = {
  auth: undefined,
  permissions: undefined,
  schemaKey: "$key",
  filter: {
    request: true,
    response: true,
  },
  validate: {
    request: true,
    response: false,
  },
  onReqError: undefined,
  onResError: undefined,
};

Inject(express, options);

With app

const app = express();

app.$post("/create-user", AddUserDto, (req, res) => {
  res.send(req.body);
});

app.$patch("/update-user", UpdateUserDto, (req, res) => {
  res.send(req.body);
});

app.$put("/add-address", CreateAddressDto, (req, res) => {
  res.send(req.body);
});

app.$get("/get-user", GetUserDto, (req, res) => {
  res.send(req.query);
});

app.$delete("/delete-address", DeleteAddressDto, (req, res) => {
  res.send(req.query);
});

With app.Route

const route = app.route("/user");
route
  .$post(AddUserDto, (req, res) => {
    res.send(req.body);
  })
  .$patch(UpdateUserDto, (req, res) => {
    res.send(req.body);
  })
  .$put(CreateAddressDto, (req, res) => {
    res.send(req.body);
  })
  .$get(GetUserDto, (req, res) => {
    res.send(req.query);
  })
  .$delete(DeleteAddressDto, (req, res) => {
    res.send(req.query);
  });

With app.Router

const router = Router();

router.$post("/create-user", AddUserDto, (req, res) => {
  res.send(req.body);
});

router.$patch("/update-user", UpdateUserDto, (req, res) => {
  res.send(req.body);
});

router.$put("/add-address", CreateAddressDto, (req, res) => {
  res.send(req.body);
});

router.$get("/get-user", GetUserDto, (req, res) => {
  res.send(req.query);
});

router.$delete("/delete-address", DeleteAddressDto, (req, res) => {
  res.send(req.query);
});

With router.Route

const router = new Router();
const route = router.route("/user");
route
  .$post(AddUserDto, (req, res) => {
    res.send(req.body);
  })
  .$patch(UpdateUserDto, (req, res) => {
    res.send(req.body);
  })
  .$put(CreateAddressDto, (req, res) => {
    res.send(req.body);
  })
  .$get(GetUserDto, (req, res) => {
    res.send(req.query);
  })
  .$delete(DeleteAddressDto, (req, res) => {
    res.send(req.query);
  });

Method 2

As a simple Express middleware.

import express, { Router } from "express";
import DTO from "express-dto";

// Your DTO files
import { GetUserDto, UpdateUserDto, AddUserDto } from "./dtos";
import CreateAddressDto from "./createAddress.dto.ts";
import DeleteAddressDto from "./deleteAddress.dto.json";

Middleware With app

const app = express();

const { middleware } = new DTO(AddUserDto.schemas, AddUserDto.options);

app.post("/create-user", middleware, (req, res) => {
  res.send(req.body);
});

const { m } = new DTO(UpdateUserDto.schemas);

app.patch("/update-user", m, (req, res) => {
  res.send(req.body);
});

const createAddressDTO = new DTO(CreateAddressDto.schemas);

app.put("/add-address", createAddress.middleware, (req, res) => {
  res.send(req.body);
});

const getUserDTO = new DTO(GetUserDto.schemas);

app.get("/get-user", getUserDTO.m, (req, res) => {
  res.send(req.query);
});

const deleteAddressDTO = new DTO(DeleteAddressDto.schemas);

app.delete("/delete-address", deleteAddressDTO.middleware, (req, res) => {
  res.send(req.query);
});

Middleware With app.Route

const { middleware } = new DTO(AddUserDto.schemas);
const { m } = new DTO(UpdateUserDto.schemas);
const createAddressDTO = new DTO(CreateAddressDto.schemas);
const getUserDTO = new DTO(GetUserDto.schemas);
const deleteAddressDTO = new DTO(DeleteAddressDto.schemas);

const route = app.route("/user");
route
  .$post(middleware, (req, res) => {
    res.send(req.body);
  })
  .$patch(m, (req, res) => {
    res.send(req.body);
  })
  .$put(createAddressDTO.middleware, (req, res) => {
    res.send(req.body);
  })
  .$get(getUserDTO.m, (req, res) => {
    res.send(req.query);
  })
  .$delete(deleteAddressDTO.middleware, (req, res) => {
    res.send(req.query);
  });

Middleware With app.Router

const router = Router();

const { middleware } = new DTO(AddUserDto.schemas);

router.post("/create-user", middleware, (req, res) => {
  res.send(req.body);
});

const { m } = new DTO(UpdateUserDto.schemas);

router.patch("/update-user", m, (req, res) => {
  res.send(req.body);
});

const createAddressDTO = new DTO(CreateAddressDto.schemas);

router.put("/add-address", createAddress.middleware, (req, res) => {
  res.send(req.body);
});

const getUserDTO = new DTO(GetUserDto.schemas);

router.get("/get-user", getUserDTO.m, (req, res) => {
  res.send(req.query);
});

const deleteAddressDTO = new DTO(DeleteAddressDto.schemas);

router.delete("/delete-address", deleteAddressDTO.middleware, (req, res) => {
  res.send(req.query);
});

Middleware With router.Route

const { middleware } = new DTO(AddUserDto.schemas);
const { m } = new DTO(UpdateUserDto.schemas);
const createAddressDTO = new DTO(CreateAddressDto.schemas);
const getUserDTO = new DTO(GetUserDto.schemas);
const deleteAddressDTO = new DTO(DeleteAddressDto.schemas);

const router = new Router();
const route = router.route("/user");

route
  .$post(middleware, (req, res) => {
    res.send(req.body);
  })
  .$patch(m, (req, res) => {
    res.send(req.body);
  })
  .$put(createAddressDTO.middleware, (req, res) => {
    res.send(req.body);
  })
  .$get(getUserDTO.m, (req, res) => {
    res.send(req.query);
  })
  .$delete(deleteAddressDTO.middleware, (req, res) => {
    res.send(req.query);
  });

Options

Settings fields marked "Will be available in the future" are settings fields created for future updates, we recommend that you use them now.

FieldTypeDefaultDescription
authfunction or undefinedundefinedChecks the user's permission to use the entpoint (Will be available in the future)
permissionsobject or undefinedundefinedChecks the user's permission to use the entpoint (Will be available in the future)
schemaKeystring$keyAllows you to create schema for non-object responses
filterobjectfilterObjectSets filtering status.
filter.requestbooleantrueChanges the request body according to the dto definition
filter.responsebooleanfalseChanges the response body according to the dto definition
validateobjectvalidateObjectSets validation status.
validate.requestbooleantrueValidate the request body according to the dto definition
validate.responsebooleantrueValidate the response body according to the dto definition
onReqErrorfunction or undefinedundefinedFunction to be triggered when request validation error occurs
onResErrorfunction or undefinedundefinedFunction to be triggered when response validation error occurs
onACLErrorfunction or undefinedundefinedFunction to be triggered when non-permission error occurs

Default Option Object

{
  auth: undefined,
  permissions: undefined,
  schemaKey: "$key",
  filter: {
    request: true,
    response: true,
  },
  validate: {
    request: true,
    response: false,
  },
  onReqError: undefined,
  onResError: undefined,
  onACLError: undefined,
}

Full Option Example

const options = {
  auth: (req) => {
    try {
      req.jwt = null;
      if (!req.headers.auth || typeof req.headers.auth !== "string") {
        return false;
      }

      const auth = req.headers.auth.split(" ");

      if (auth[0] !== "Bearer" || !auth[1]) {
        return false;
      }

      req.jwt = jwt.verify(auth[1], config.jwtKey);

      if (result) {
        return req.jwt.permissions;
      } else {
        return false;
      }
    } catch (err) {
      req.jwt = null;
      return false;
    }
  },
  permissions: {
    user: ["read", "write"], // OR user:'reader'
  },
  schemaKey: "$custom",
  filter: {
    request: true,
    response: true,
  },
  validate: {
    request: true,
    response: true,
  },
  onReqError(req, res, next, message) {
    next(message);
  },
  onResError: (req, res, next, message) => {
    res.status(500).send({
      message: "Please contact the development team",
      code: "001",
    });
  },
  onACLError(req, res, next, message) {
    res.status(401).json({
      message: "You are not authorized",
      code: "002",
    });
  },
};

Methods

DTO

import DTO from "express-dto";

const { middleware } = new DTO(schemas, options);

Inject

import express from "express";
import { Inject } from "express-dto";

Inject(express, options);

SetDefaults

import { SetDefaults } from "express-dto";

SetDefaults(options);

Create DTO File

export default {
  schemas:{
    title: "Register",
    description: "Create new user",
    groups: ["auth"],
    request: requestSchema
    response: responseSchemas
  },
  options: optionObject
}

Request Schema

export default {
  title: "Register",
  description: "Create new user",
  schema: Mongoose.Schema.definition,
};

Response Schema

export default {
  title: "Register",
  description: "Create new user",
  schemas: {
    201: {
      title: "User Created",
      description: "If user created successfully",
      schema: { $key: { type: String } },
    },
    400: {
      title: "User not created",
      description: "If user not created",
      schema: { code: { type: String, default: "AUTHX004" } },
    },
    409: [
      {
        title: "Conflict",
        description: "If email already exists",
        schema: {
          username: { type: String },
          code: { type: String, default: "ERRORx001" },
        },
      },
      {
        title: "Conflict",
        description: "If username already exists",
        schema: {
          username: { type: String },
          code: { type: String, default: "ERRORx001" },
        },
      },
    ],
  },
};

Full Schema Example

import { Document } from "mongoose";
import validator from "validator";
import { ErrorMessage, Request, Response, NextFunction } from "../src/types";
export interface IRequestDocument extends Document {
  photo: string;
  language: string;
  name: string;
  middleName?: string;
  surname: string;
  username?: string;
  email?: string;
  phone?: string;
  password: string;
  refCode?: string;
}

const schemas = {
  title: "Register",
  description: "Create new user",
  groups: ["auth"],
  request: {
    title: "Register",
    description: "Create new user",
    schema: {
      photo: { type: String, default: "/defaults/profile.png", required: true },
      language: {
        type: String,
        enum: ["en", "tr", "ru"],
        default: "en",
      },
      name: {
        type: String,
        required: true,
      },
      middleName: {
        type: String,
      },
      surname: {
        type: String,
        required: true,
      },
      username: {
        type: String,
        required(this: IRequestDocument) {
          return !this.email && !this.phone;
        },
      },
      email: {
        type: String,
        required(this: IRequestDocument) {
          return !this.username && !this.phone;
        },
        validate: {
          validator: (value: string) => validator.isEmail(value),
          message: "email",
        },
      },
      phone: {
        type: String,
        required(this: IRequestDocument) {
          return !this.email && !this.username;
        },
        validate: {
          validator: (value: string) =>
            validator.isMobilePhone(value, undefined, { strictMode: true }),
          message: "phone",
        },
      },
      password: {
        type: String,
        required: true,
      },
      refCode: {
        description: "Referral Code",
        type: String,
      },
    },
  },
  response: {
    schemas: {
      201: {
        title: "User Created",
        description: "If user created successfully",
        schema: { id: { type: String } },
      },
      400: {
        title: "User not created",
        description: "If user not created",
        schema: { code: { type: String, default: "AUTHX004" } },
      },
      409: [
        {
          title: "Conflict",
          description: "If email already exists",
          schema: {
            username: { type: String },
            code: { type: String, default: "ERRORx001" },
          },
        },
        {
          title: "Conflict",
          description: "If username already exists",
          schema: {
            username: { type: String },
            code: { type: String, default: "ERRORx001" },
          },
        },
      ],
    },
  },
};

const options = {
  filter: {
    request: true,
    response: true,
  },
  validate: {
    request: true,
    response: true,
  },
  onReqError(
    _req: Request,
    _res: Response,
    next: NextFunction,
    message: ErrorMessage
  ) {
    next(message);
  },
  onResError(
    _req: Request,
    res: Response,
    _next: NextFunction,
    message: ErrorMessage
  ) {
    res.send({
      message: "Please contact the development team",
      code: message.code,
    });
  },
};

export default { schemas, options };

Roadmap

  • Add Request Validation
  • Add Response Validation
  • Add Data Filter
  • Add Router Medhods
  • Add ACL Integration
  • Add Swagger Integration

See the open issues for a full list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Rohan Acar :wave: hi@rohanacar.com

Project Link: https://github.com/rohanacar/express-dto

0.2.71

2 years ago

0.2.7

2 years ago

0.2.6

2 years ago

0.2.5

2 years ago

0.2.4

2 years ago

0.2.3

2 years ago

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.0

2 years ago