@dechamp/express-auto-route
TypeScript icon, indicating that this package has built-in type declarations

1.8.3 • Public • Published

Express Auto Route

An express auto route module which allows routes and middleware to be configured via config file.

Setup

The express auto route is fairly simple to setup. It just takes an instance of express server, an array of route configs, and optional array of middleware. It comes with some default middleware for json schema validation. Our setup example will implement those middleware in the setup.

Step 1

Include the module. Depending on which module system you're using, you can setup it up a few ways. We export both the namespaced module and the default for convenience.

note: RouteRequestJsonSchemaValidator and RouteResponseJsonSchemaValidator middleware are optional if you do not need schema validation. You can mix and match as you please or even write your own.

// commonjs
const {AutoRoute, RouteRequestJsonSchemaValidator, RouteResponseJsonSchemaValidator} = require('express-auto-route');

// or es6 syntax
import {
    AutoRoute,
    RouteRequestJsonSchemaValidator,
    RouteResponseJsonSchemaValidator,
    Route,
    Methods
} from "@dechamp/express-auto-route";

// or es6 syntax with default
import AutoRoute, {
    RouteRequestJsonSchemaValidator,
    RouteResponseJsonSchemaValidator,
    Route,
    Methods
} from "@dechamp/express-auto-route";
//express server
const server = ...;
// see exmple below.
const routes = ...;

AutoRoute({
  server,
  routes,
  middlewares: [
    RouteRequestJsonSchemaValidator,
    RouteResponseJsonSchemaValidator,
    // your custom middleware
  ],
});

Step 2

Setup a route. There are advanced options for routes which we'll show further down but for now let's just do the basics.

Route config example

If you wanted to add a "home" route then below is an example of it.

  • id: any unique id you feel fit, typically route name and method (post, get, put, delete...)
  • method: see exported typescript enum, Methods. or quick reference below. This would be what you would use for the express route method.
    • GET
    • POST
    • HEAD
    • PUT
    • DELETE
    • USE
    • if you need one not listed, please email me or submit a merge request
  • modulePath: the path to the express module (req, res, next) => ..., this can be async as well. Typically follows "routes//" and extension is optional just like with normal module import would be.
  • path: This is your url path. example, "/home" points to https://localhost/home. You can refer to express path, which inturn uses path-to-regex
const routes = [
    {
        id: "homeGet",
        method: "GET",
        modulePath: "/routes/home/get.js",
        path: "/home"
    },
    // ...
]

Route Middleware

Route middleware can be setup in two ways. There is the option to apply middleware to all routes, when adding it via initialization of the AutoRoute, which will apply to all routes, then there also the option to add via the route itself which applies to only the single route.

Using the same example as above, we'll setup the route middleware using the "apply to all" option.

The 'RouteRequestJsonSchemaValidator' and 'RouteResponseJsonSchemaValidator' middleware require you add in the json middleware for express, to convert params to json, via server.use(express.json());

// see other examples above if you use es6 "import" method.
const {AutoRoute, RouteRequestJsonSchemaValidator, RouteResponseJsonSchemaValidator} = require('express-auto-route');

AutoRoute({
  server,
  routes,
  middlewares: [ // These apply to all routes, and enable more options per route
    RouteRequestJsonSchemaValidator,
    RouteResponseJsonSchemaValidator,
    // your custom middleware
  ],
});

If you wanted to add a "resource" route with json schema validation using the 'RouteResponseJsonSchemaValidator' middlware, then below is an example of it. This route has a response json schema validation by adding responseJsonSchema option to each route. This option gets enabled via the 'RouteResponseJsonSchemaValidator'

note: Please refer to docs/schemaExamples for real schemas used in our examples below.

const routes = [
    {
        id: "resourceGet",
        method: "GET",
        modulePath: "/routes/resource/get.js",
        path: "/resources",
        responseJsonSchema: "/path/to/schemas/resources.schema.json", // this only works due to using the RouteResponseJsonSchemaValidator middleware
        middleware: [] // an array of paths to middleware that applies to this route only. This is a standard express middleware (req, res, next) => {}
    },
    // ...
]

We can add another route to retrieve an single resource by a uuid, by adding this to the array of routes. We will add validation to the request query by using the requestJsonSchema.query option, which was enabled via 'RouteRequestJsonSchemaValidator' middleware.

const routes = [
    //previous route added previously... ,
    {
        id: "resourceGetUuid",
        method: "GET",
        modulePath: "/routes/resource/get.js",
        path: "/resources/:uuid",
        requestJsonSchema: {
            query: "/path/to/schemas/getByUuid.schema.json" // This key was made available via 'RouteRequestJsonSchemaValidator'
        },
        responseJsonSchema: "/path/to/schemas/resource.schema.json"
    }
]

We can also run validation against the path params such as :name, using the requestJsonSchema.params option, which was enabled via 'RouteRequestJsonSchemaValidator' middleware. You can validate any path params using this methods, as it runs against the req.params. See the express path/path-to-regex npm modules as mentioned above, to see what populates for the params.

const routes = [
    //previous route added previously... ,
    {
        id: "resourceGetUuid",
        method: "GET",
        modulePath: "/routes/resource/get.js",
        path: "/resources/:uuid",
        requestJsonSchema: {
            params: "/path/to/schemas/params.schema.json" // This key was made available via 'RouteRequestJsonSchemaValidator'
        },
        responseJsonSchema: "/path/to/schemas/resource.schema.json"
    }
]

We have the option to validate against the request body as well. Just by providing a path to a schema file via requestJsonSchema.body, which again was made available via 'RouteRequestJsonSchemaValidator'

const routes = [
    //previous route added previously... ,
    {
        id: resourcePost,
        method: POST,
        path: "/resources",
        modulePath: "/routes/resource/post.js",
        requestJsonSchema: {
            body: "/path/to/schemas/resource.schema.json" // This was made available via 'RouteRequestJsonSchemaValidator'
        },
        responseJsonSchema: "/path/to/schemas/resource.schema.json"
    }
]

As mentioning above, we can add middleware to a single route if we wanted, via the "middleware" config within each route object. This an array, so you can add as many as you want. For brevity, we'll just add an inline middleware that console logs a message.

const routes = [
    //previous route added previously... ,
    {
        id: "homeGet",
        method: "GET",
        path: "/home",
        modulePath: "/routes/home/post.js", // extension .js is not needed.
        middleware: [
           "/routes/home/middleware.js" // extension .js is not needed.
        ] 
    }
]

Advanced configs

At this time, there is only one additional config, which is setting the route base path. This will let you point to the routes folder to avoid replicating it for each route. To set this, you add 'routeBasePath' to the config params when you initialize the AutoRoute. This could be useful for version control as well.

const app = //express instance
const routes = { /*...*/ };
AutoRoute({
    server: app,
    routeBasePath: `./routes`,
    routes,
    middlewares: [
        RouteRequestJsonSchemaValidator,
        RouteResponseJsonSchemaValidator
    ]
});

Now we can shorten up the routes, removing the route base path we declared above.

// We will go from this...
const routes = [
    {
        id: "homeGet",
        method: "GET",
        path: "/home",
        modulePath: "/routes/home/post.js", // extension .js is not needed.
        middleware: [
           "/routes/home/middleware.js" // extension .js is not needed.
        ] 
    }
]

// to this, removing the /routes and while we are at it remove the extensions.
const routes = [
    {
        id: "homeGet",
        method: "GET",
        path: "/home",
        modulePath: "/home/post",
        middleware: [
           "/home/middleware"
        ] 
    }
]

Readme

Keywords

Package Sidebar

Install

npm i @dechamp/express-auto-route

Weekly Downloads

1

Version

1.8.3

License

ISC

Unpacked Size

68.2 kB

Total Files

39

Last publish

Collaborators

  • dechamp