Comments (21)
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.
from json-server.
@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"
from json-server.
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,
from json-server.
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)
from json-server.
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?
from json-server.
Any updates?
from json-server.
Using @ChrisShen93 and @snecker tips I made this example : https://github.com/JeanReneRobin/json-server-multiple-files
from json-server.
Why to increase the complexity of the project. This project is famous for simplicity that allows quick prototyping.
from json-server.
@kptcs and @alexkreidler - Can you guys check this example if it is useful in your case?
https://github.com/dharaghodasara/JSON-Mock-Server
from json-server.
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.
from json-server.
Hey @typicode , curious on this point as well, I need the functionality but with the database changes to be persisted.
Any way around this?
from json-server.
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?
from json-server.
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);
from json-server.
@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)
from json-server.
@ylacaute
Well, what my code was doing is just splitting "db.json" into different files.
from json-server.
@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.
from json-server.
@typicode
We could do this improvement :
- if you give a file as db in CLI, you change nothing
- if you give a directory, that means you have to aggregate all the json files inside
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();
};
from json-server.
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.
from json-server.
@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.
from json-server.
I took @snecker's solution, it worked except no data persistence. Which of other solutions would keep the newly generated data written in file?
from json-server.
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
from json-server.
Related Issues (20)
- SyntaxError: Unexpected token '||=' HOT 1
- Please, bring back the `--delay` option HOT 2
- CORS Issue (Access-Control-Allow-Headers)
- _sort=id&_order=desc do not work (--version 1.0.0-beta.0) HOT 1
- paginate should return empty data when there have a bigger `_page`, but return last page data now
- `_like` doesn't work anymore? HOT 1
- _dependent value error
- Licensing HOT 1
- Compressed Uploads
- Getting nested resources doesn't work HOT 1
- cant find package json-server within node_modules HOT 3
- delay [ms] is not working for me...... HOT 2
- I can not not increased by 1 for id HOT 1
- Newly added data is not recognized when trying to update it seconds later HOT 1
- multiple files with beta 1.0.0v1 HOT 1
- How to access multiple layers, for example /system/user system/menu HOT 3
- Pagination fetches all Objects instead of just one page HOT 3
- Implicit foreign key mapping not working
- Logs not logging in terminal HOT 3
- File not found HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from json-server.