json-server icon indicating copy to clipboard operation
json-server copied to clipboard

Multiple files

Open nzmedet opened this issue 11 years ago • 21 comments

Would be very useful to serve directory, rather than 1 file. Say you got accounts.json, and flight.json, would be great to call something json server src/app/db/. and ability to call localhost:3000/accounts for accounts file

nzmedet avatar Feb 02 '15 10:02 nzmedet

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.

typicode avatar Feb 02 '15 19:02 typicode

Hey @typicode , curious on this point as well, I need the functionality but with the database changes to be persisted.

Any way around this?

Celestz avatar May 21 '15 17:05 Celestz

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?

typicode avatar May 21 '15 23:05 typicode

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.

altano avatar Jun 11 '15 07:06 altano

Why to increase the complexity of the project. This project is famous for simplicity that allows quick prototyping.

gagan-bansal avatar Jun 11 '15 10:06 gagan-bansal

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?

yesarpit avatar Jul 09 '15 10:07 yesarpit

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);

mcolomerc avatar Oct 27 '15 18:10 mcolomerc

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 avatar Feb 06 '17 09:02 snecker

@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"

yhshen93 avatar Aug 09 '17 02:08 yhshen93

@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 avatar Aug 09 '17 11:08 ylacaute

@ylacaute Well, what my code was doing is just splitting "db.json" into different files.

yhshen93 avatar Aug 10 '17 00:08 yhshen93

@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.

ylacaute avatar Aug 12 '17 07:08 ylacaute

@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();
};

ylacaute avatar Aug 12 '17 08:08 ylacaute

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.

jai18881 avatar Oct 12 '17 04:10 jai18881

@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.

RyanThomas95 avatar Dec 06 '17 20:12 RyanThomas95

I took @snecker's solution, it worked except no data persistence. Which of other solutions would keep the newly generated data written in file?

inmchfw avatar Jan 03 '18 09:01 inmchfw

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

KNeela avatar Jan 22 '18 14:01 KNeela

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,

kptcs avatar May 22 '18 06:05 kptcs

Any updates?

alexkreidler avatar Aug 20 '18 23:08 alexkreidler

@kptcs and @alexkreidler - Can you guys check this example if it is useful in your case?

https://github.com/dharaghodasara/JSON-Mock-Server

dharaghodasara avatar Feb 24 '19 05:02 dharaghodasara