Open vko-online opened 9 years ago
Nice idea. With the current version you can achieve it somehow using a .js
file:
// db.js
module.exports = function() {
return {
accounts: require('./accounts.json')
flight: require('./flight.json')
}
}
However changes to database won't be persisted.
Hey @typicode , curious on this point as well, I need the functionality but with the database changes to be persisted.
Any way around this?
Hey @Celestz
I don't have any great solution for that. But, with the recents versions you can do this:
var jsonServer = require('json-server')
var server = jsonServer.create()
server.use(jsonServer.defaults)
server.use('/db1', jsonServer.router('db1.json'))
server.use('/db2', jsonServer.router('db2.json'))
server.listen(3000)
Changes will be saved in 2 files, but you'll have routes like this db1/resources/id
which is not very beautiful and you wont be able to have relationships between the 2 files.
You can also use a db.js
file and create snapshots using s
in the terminal.
Is it to organize code?
I'm in favor of this as well. I'm going to be using this to stub out a fairly large dataset and I'd rather have each resource in its own file. I can deal without it but it would be nice if you get around to it. Thanks for the awesome project.
Why to increase the complexity of the project. This project is famous for simplicity that allows quick prototyping.
How to split db into files? I havent seen details in guide provided. If the functionality is there can we please get latest version via npm?
Just read the directory and create a db object with all JSON files:
var db = {};
var files = fs.readdirSync(jsonfolder);
files.forEach(function (file) {
if (path.extname(jsonfolder + file) === '.json') {
db[path.basename(jsonfolder + file, '.json')] = require(path.join(jsonfolder,file));
}
});
// Returns an Express server
var server = jsonServer.create();
// Set default middlewares (logger, static, cors and no-cache)
server.use(jsonServer.defaults());
// Returns an Express router
var router = jsonServer.router(db);
server.use(router);
server.listen(port);
you can merge all property of multiple file into on obj,like this
var _ = require("underscore")
var path = require('path')
var fs = require('fs')
var base = {};
var files = fs.readdirSync(mockDir);
files.forEach(function (file) {
_.extend(base, require(path.resolve(mockDir, file)))
});
var router = jsonServer.router(base)
server.use(router)
@snecker provided a nice solution I implement like these:
/**
* json-server.index.js
*/
const path = require('path')
const fs = require('fs')
const _ = require('lodash')
const jsonServer = require('json-server')
const server = jsonServer.create()
const port = 3002
let obj = {}
let files = fs.readdirSync(path.resolve(__dirname, '../test/mock/'))
files.forEach((file) => {
if (file.indexOf('.json') > -1) {
_.extend(obj, require(path.resolve(__dirname, '../test/mock/', file)))
}
})
const router = jsonServer.router(obj)
server.use(jsonServer.defaults())
server.use(router)
server.listen(port, () => {
console.log(`JSON Server is running at ${port}`)
})
Add nodemon into package.json
## script
"start:server": "nodemon --watch test/mock json-server.index.js"
@ChrisShen93
Until now, I was using json-server in a simple way :
json-server db.json --routes routes.json
From your comment, I understand we could split "routes.json" in different files.
Is it possible to do the same for db.json ? (json responses)
@ylacaute Well, what my code was doing is just splitting "db.json" into different files.
@ChrisShen93 Sorry, I read too fast. Your solution works, and in order to keep routes rewriting we can do that :
const routesFile = path.resolve(__dirname, "routes.json");
let createUrlRewriter = () => {
const routes = JSON.parse(fs.readFileSync(routesFile));
return jsonServer.rewriter(routes);
};
server.use(createUrlRewriter());
But i finaly don't like this solution because you lose all json-server CLI options... That is definitevely not a durable solution.
For now I prefer @typicode solution. Again, in order to keep routes rewriting feature, we need to aggregate data directly with Object.assign, for example :
// db.js
module.exports = function() {
return Object.assign({},
require('./mock/jira.json'),
require('./mock/jenkins.json'));
};
Trying to persist mocks doesn't seem to be a good idea.
@typicode We could do this improvement :
Today I use the code below but it could be generic.
import path from 'path';
import fs from 'fs';
const mockDirectory = path.resolve(__dirname, 'mock');
let createDB = () => {
const files = fs.readdirSync(mockDirectory);
let mocks = {};
files.forEach((file) => {
if (file.indexOf('.json') > -1) {
Object.assign(mocks, require(mockDirectory + "/" + file));
}
});
return mocks;
};
module.exports = function() {
return createDB();
};
My solution is similar to @typicode's. I am using a db.js where I am consolidating all the jsons and exporting a db object, strigifying it and then generating a db.json using fs. This way, I don't have to maintain a huge db.json manually and all api mocks are maintained in separate json files.
@typicode Your solution works great! Anyway to change this to ES2015? I'm running the command using npm run json-server --watch mock-data/db.js --port 3001
. I thought I could use a middleware but it still was not working for some reason. Thanks.
I took @snecker's solution, it worked except no data persistence. Which of other solutions would keep the newly generated data written in file?
Does someone have a project example I could look at on git? I tried the solutions above, but I can't really figure out what I'm doing wrong
I have three api, one is for /employee, other one for /projects and third one for /city I would like to access my all these api like this localhost:3000/employee localhost:3000/projects localhost:3000/city
But json-server --watch db.json will watch only single file, I need to watch 3 json file, please guide
@typicode any help would be appreciated.
Thanks,
Any updates?
@kptcs and @alexkreidler - Can you guys check this example if it is useful in your case?
Using @ChrisShen93 and @snecker tips I made this example : https://github.com/JeanReneRobin/json-server-multiple-files
Would be very useful to serve directory, rather than 1 file. Say you got
accounts.json
, andflight.json
, would be great to call somethingjson server src/app/db/.
and ability to calllocalhost:3000/accounts
for accounts file