Skip to content

feat: allow entering the next middleware when accessing a route with no defined data. #1330

Closed
@wll8

Description

@wll8

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch json-server@0.17.0 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/json-server/lib/server/router/index.js b/node_modules/json-server/lib/server/router/index.js
index a11d834..1f9d8ca 100644
--- a/node_modules/json-server/lib/server/router/index.js
+++ b/node_modules/json-server/lib/server/router/index.js
@@ -29,6 +29,7 @@ const mixins = require('../mixins');
 module.exports = (db, opts) => {
   opts = Object.assign({
     foreignKeySuffix: 'Id',
+    _noDataNext: false,
     _isFake: false
   }, opts);
 
@@ -82,14 +83,17 @@ module.exports = (db, opts) => {
     const msg = `Type of "${key}" (${typeof value}) ${sourceMessage} is not supported. ` + `Use objects or arrays of objects.`;
     throw new Error(msg);
   }).value();
-  router.use((req, res) => {
+  const render = (req, res) => {
     if (!res.locals.data) {
       res.status(404);
       res.locals.data = {};
     }
 
     router.render(req, res);
-  });
+  }
+  const keys = Object.keys(db.value()).map(key => `/${key}`)
+  opts._noDataNext && keys.length && router.use(keys, render)
+  !opts._noDataNext && router.use(render);
   router.use((err, req, res, next) => {
     console.error(err.stack);
     res.status(500).send(err.stack);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions