req.headers
is the object of the headers sent from the client
const isAuthorized = (req) => {
return req.headers['AUTH_TOKEN'] ? true : false;
}
I have a nice solution using --middleware ;)
package.json:"startAPI": "json-server --watch server/mockedBackendAPI.json --routes server/mockedBackendRoutes.json --port 3004 --middlewares server/middleware.js"
middleware.js:module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
@TW-OY
save this following code in a file called middlewares
module.exports = (req, res, next) => {
console.log('url', req.url);
console.log('path', req.path);
if (req.url == '/test') {
res.redirect('/');
}else{
next();
}
};
then run json-server as follow:
json-server db.json --middlewares middlewares.js
browse:
http://localhost:3000/test
or if you want more generic way of handling your static assets, you could use --static
option in the command line
create public/assets/index.html
file create directories if not exist
json-server db.json --static public
http://localhost:3000/assets
will serve public/static/index.html
.. and so on
I have models with optional relations to eachother and have a problem with DELETE
.
The data for a model foo
could look like this initially:
{
"foos": [
{
"id": 1,
"title": "A foo"
}
]
}
After adding a bar
and connecting it to my foo
it would look like this:
{
"foos": [
{
"id": 1
"title": "A foo",
"barId": 1
}
],
"bars": [
{
"id": 1
"title": "A bar"
}
]
}
Now I want to DELETE
the foo
with id 1
. But I don't want to delete the bar
. Speaking in terms of SQL I do not want an ON DELETE CASCADE
as it looks like it is doning now. In case I DELETE
the bar
instead I would like the barId
property in the foo
to either be set to undefined
(like with ON DELETE SET NULL
) or just removed from the foo
object.
Is this possible with json-server today?
@PerWiklander short answer. No.
Long answer:json-server
is an express server so you can do all kind of workarounds you wish.
You should first use json-server as module not CLI.
Giving that json-server db is in json-server router object
One workaround on my mind now is to write a simple middleware that intercept DELETE /foos/:fooID
then using lowdb's API, get thebar
by its id
, update the value, then save the db db.write()
Please find my anser here, might help too
please let me know if this is not clear so I can find sometime to create an example for you.
@typicode
.render
method but in TypeScript with @types/json-server this method does not exist. What I need to do is convert body of response from object[] to { data: object[], totalCount: header.get('X-Total-Count') }.
index.js
example and the server.js
example
Is there a way to use router.render
conditionally based on route?
i.e. I'm trying to do something like below in routes.js but only for a GET request on an endpoint, let's say GET /clients
. I have custom middleware files working but don't quite understand how to pass the (req, res, next) information to the render function as well.
routes.js
const { metadataResponseWrapper } = require('./wrapper');
module.exports = (server, router) => {
router.render = metadataResponseWrapper({pageSize: 3});
};
server.js
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const middlewares = jsonServer.defaults();
const configureRoutes = require('./routes');
configureRoutes(server, router);
server.use(middlewares);
server.use(router);
server.use(jsonServer.bodyParser);
server.use(middlewares);
server.use(router);
server.listen(3001);
module.exports = (util) => {
return {
api: {
// For example, permission checks can be created at all entry points
'use /' (req, res, next) {
if(req.headers.token === undefined) {
res.status(403).json({msg: `No permission`})
} else {
next()
}
},
// Intercepts any requests sent to db.json, and responses from db.josn
'patch /books/:id' (req, res, next) { // intercept config.db
req.body.a = `111` // Modify the data passed in by the user
next()
res.mm.resHandleJsonApi = async (arg) => {
arg.data.a = `222` // Modify the response, it will not be stored in db.json
return arg.resHandleJsonApi(arg)
}
},
},
db: {
books: [
{
id: 1,
title: `css`,
},
],
},
}
}