typicode / json-server

Get a full fake REST API with zero coding in less than 30 seconds (seriously)
Other
71.92k stars 6.94k forks source link

Add custom routes to expressJS app with json-server #475

Open NikitaKharkov opened 7 years ago

NikitaKharkov commented 7 years ago

I'm not strong in expressJS, so I guess I miss some little configuration.

I need to include in my expressJS rewrite non-standart routes. How can I do it? I was trying to write app.use(dbserver.rewriter('./routes.json')); or app.use(dbserver.rewriter(fs.readFileSync'(./routes.json'))); or app.use(dbserver.rewriter({"customer/search/:id": "/customer?owner=:id"}));

and all that in different places. And always I got 404 page code. So where am I wrong? Thanks.

typicode commented 7 years ago

Hi @NikitaKharkov,

rewriter only accepts an object, so you can write:

app.use(dbserver.rewriter(JSON.parse(fs.readFileSync'(./routes.json'))))

// or

app.use(dbserver.rewriter({"customer/search/:id": "/customer?owner=:id"}))

You should probably call in the same place you use() your other middlewares (like index.js or app.js) and call rewriter once with all the desired routes.

Hope it will help and feel free to share more code if you want.

NikitaKharkov commented 7 years ago

My code is: `app.start = function () { var server = app.listen(app.get('port'), app.get('host'), function(){ app.emit('started');

    var host = server.address().address;
    var port = server.address().port;

    console.log('API listening at http://%s:%s', host, port);

    process.on('SIGINT', function () {
      console.log('API has shutdown.');
      console.log('API was running for %s seconds.', Math.round(process.uptime()).toString());
      process.exit(0);
    });
  });

  return server;
};

// Custom routes
// Find customers by items in fieldsForSearch array
app.get('/customer/search', function (req, resp) {
    var result = [];
    var searchValueReg = new RegExp('.*' + req.query.queryMain + '.*', 'ig');
    var fieldsForSearch = ['customerId', 'companyKey', 'companyName', 'firstname', 'lastname'];
    var customers = db.customer;
    customers.forEach(function (customer) {
        for (var fieldName in customer) {
            if (fieldsForSearch.indexOf(fieldName) > -1 && searchValueReg.test(customer[fieldName])) {
                result.push(customer);
            }
        };
    });

    if (result.length == 0) {
        resp.send(db.customer);
    } else {
        resp.send(result);
    }

});

app.use(dbserver.rewriter({"customer/search/:id": "/customer?owner=:id"}))

app.set('host', '0.0.0.0');
app.set('port', 3000);
app.set('etag', false);

app.use(cors());
app.use(dbserver.defaults);
app.use(dbserver.router(db));

app.use(parser.json());
app.use(parser.urlencoded({extended: true}));

Answer in terminal: GET /customer/search/id_3 404 6.342 ms - 2`