npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-dto

v0.2.71

Published

Mongoose-based, swagger-compliant request, response and permission validation middleware for Express.js

Downloads

6

Readme

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.

| Field | Type | Default | Description | | :---------------- | :-------------------- | :------------- | :--------------------------------------------------------------------------------- | | auth | function or undefined | undefined | Checks the user's permission to use the entpoint (Will be available in the future) | | permissions | object or undefined | undefined | Checks the user's permission to use the entpoint (Will be available in the future) | | schemaKey | string | $key | Allows you to create schema for non-object responses | | filter | object | filterObject | Sets filtering status. | | filter.request | boolean | true | Changes the request body according to the dto definition | | filter.response | boolean | false | Changes the response body according to the dto definition | | validate | object | validateObject | Sets validation status. | | validate.request | boolean | true | Validate the request body according to the dto definition | | validate.response | boolean | true | Validate the response body according to the dto definition | | onReqError | function or undefined | undefined | Function to be triggered when request validation error occurs | | onResError | function or undefined | undefined | Function to be triggered when response validation error occurs | | onACLError | function or undefined | undefined | Function 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

  • [x] Add Request Validation
  • [x] Add Response Validation
  • [x] Add Data Filter
  • [x] 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: [email protected]

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