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-joi-routes

v1.0.1

Published

Module for Express.js that allows you to standardize your routes and validate their content with Joi.

Downloads

17

Readme

Express Joi Routes

npm version npm downloads build status converage status license

Module for Express.js that allows you to standardize your routes and validate their content with @happi/joi.

Table of Content

About

The motivation to use this package is improve the maintainability of your code and facilitate DRY (Don't repeat yourself) principle in your routes.

Features

This library support the following features:

  • Create routes.
  • Add middleware(s) to routes.
  • Add Joi validators (@happi/joi) to routes.
  • Set prefix to your routes.

Installation

npm i --save express-joi-routes

Example

Here is an example to use express-joi-routes in the simplest way.

JavaScript

'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const { createRoutes, Method } = require('express-joi-routes');

class Controller {
  getOne(_req, res) {
    res.json({
      message: 'ok',
    });
  }
}

app.use(bodyParser.json());

const routes = [
  {
    route: '/foo',
    method: Method.Get,
    controller: Controller,
    handler: 'getOne',
  },
];

app.use(createRoutes(routes));
app.listen(3000, () => {
  console.log('Listening on port 3000');
});

TypeScript

import express, { Request, Response } from 'express';
import bodyParser from 'body-parser';
import { createRoutes, Method, Routes } from 'express-joi-routes';

class Controller {
  public getOne(_req: Request, res: Response): void {
    res.json({
      message: 'ok',
    });
  }
}

const app: express.Express = express();
app.use(bodyParser.json());

const routes: Routes = [
  {
    route: '/foo',
    method: Method.Get,
    controller: Controller,
    handler: 'getOne',
  },
];

app.use(createRoutes(routes));
app.listen(3000, () => {
  console.log('Listening on port 3000');
});

Documentation

Routes definitions

In Express Joi Routes you can build your own routes using defined objects. The composition of these objects allows to you implement your routes with the flexibility as you want.

Route

export interface Route {
  route: string;
  method: Method;
  controller: any;
  handler: string;
  middlewares?: RequestHandler[];
  validators?: ValidatorOptions[];
}

ProxyRoute

export interface ProxyRoute {
  route: string;
  subRoutes: Routes;
  middlewares?: RequestHandler[];
}

Routes

type Routes = Array<Route | ProxyRoute>;

Example

import { Routes, Method } from 'express-joi-routes';
import { FooController } from 'controllers';

const fooRoutes: Routes = [
  {
    route: '',
    method: Method.Post,
    controller: FooController,
    handler: 'postOne',
  },
  {
    route: '/:id',
    method: Method.Get,
    controller: FooController,
    handler: 'getOne',
  },
];

const mainRoutes: Routes = [
  {
    route: '/foo',
    subRoutes: fooRoutes,
  },
];

// Equivalent to:
// POST   /foo
// GET    /foo/:id

ValidationOptions

interface ValidatorOptions {
  type: ContainerTypes;
  schema: ObjectSchema;
  opts?: ExpressJoiContainerConfig;
}

Method

Object (enum in TS) that includes all HTTP methods (supported by express.js 4.x).

Method.All;
Method.Get;
Method.Post;
Method.Put;
Method.Patch;
Method.Delete;
Method.Head;
Method.Options;
Method.Trace;
Method.Copy;
Method.Lock;
Method.Mkcol;
Method.Move;
Method.Purge;
Method.Profind;
Method.Proppatch;
Method.Unlock;
Method.Report;
Method.Mkactivity;
Method.Checkout;
Method.Merge;
Method.MSearch;
Method.Notify;
Method.Subscribe;
Method.Unsubscribe;
Method.Search;
Method.Connnect;

ContainerTypes

Object (enum in TS) that includes the validation types (see express-joi-validation).

ContainerTypes.Body;
ContainerTypes.Query;
ContainerTypes.Headers;
ContainerTypes.Fields;
ContainerTypes.Params;

ExpressJoiRoutes([options])

Class that instance a ExpressJoiRoutes object allowing to you pass a set of options to configure it.

Arguments (Typed)
ExpressJoiRoutes();
ExpressJoiRoutes(options: ExpressJoiRoutesOptions);

| ExpressJoiRoutesOptions | Description | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | joiPassError | Equivalent to passError option of express-joi-validation package. | | joiStatusCode | Equivalent to statusCode option of express-joi-validation package. |

Example
import { ExpressJoiRoutes } from 'express-joi-routes';

// With default options
const ejr: ExpressJoiRoutes = new ExpressJoiRoutes();
// With options
const ejr: ExpressJoiRoutes = new ExpressJoiRoutes({ passError: true, statusCode: 500 });

add(routes[,prefix][,middlewares])

Method that add(s) route(s) to Router object (Express.js Router), passing the following arguments:

Arguments (Typed)
add(routes: Routes): void
add(routes: Routes, prefix: string): void
add(routes: Routes, prefix: string, middlewares: any[]): void

| Argument | Type | Optional | Description | | ----------- | ---------------- | -------- | -------------------------------------------------- | | routes | Routes | no | Array with route configurations. | | prefix | string | yes | Prefix of all routes that you pass. Ex.: /api/v1 | | middlewares | RequestHandler[] | yes | Array of middleware handlers. |

Example
import { ExpressJoiRoutes, Method } from 'express-joi-routes';
// imports...
const ejr: ExpressJoiRoutes = new ExpressJoiRoutes();
const routes: Routes = [
  {
    route: 'foo',
    method: Method.Get,
    controller: ControllerClass,
    handler: 'getOne',
  },
];

ejr.add(routes, '/api/v1');

getRoutes()

Method that return a Router object (Express.js Router) with the routes added by add method.

Example
const router: Router = ejr.getRoutes();
app.use(router);

createRoutes(routes[,prefix][,middlewares])

Function that under the hood utilize ExpressJoiRoutes class to create and get routes (Router) without call the above methods.

Arguments (Typed)
add(routes: Routes): Router
add(routes: Routes, prefix: string): Router
add(routes: Routes, prefix: string, middlewares: any[]): Router

| Argument | Type | Optional | Description | | ----------- | ---------------- | -------- | -------------------------------------------------- | | routes | Routes | no | Array with route configurations. | | prefix | string | yes | Prefix of all routes that you pass. Ex.: /api/v1 | | middlewares | RequestHandler[] | yes | Array of middleware handlers. |

Example
import { createRoutes, Method } from 'express-joi-routes';
// imports, express instance, etc.

const routes: Routes = [
  {
    route: 'foo',
    method: Method.Get,
    controller: ControllerClass,
    handler: 'getOne',
  },
];

const router: Router = createRoutes(routes);
app.use(router);

License

MIT