typicode / json-server

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

Multiple files #45

Open vko-online opened 9 years ago

vko-online commented 9 years ago

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

typicode commented 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.

Celestz commented 9 years ago

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

Any way around this?

typicode commented 9 years ago

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?

altano commented 9 years ago

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.

gagan-bansal commented 9 years ago

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

yesarpit commented 9 years ago

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?

mcolomerc commented 9 years ago

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);
snecker commented 7 years ago

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)
ChrisShen93 commented 7 years ago

@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"
ylacaute commented 7 years ago

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

ChrisShen93 commented 7 years ago

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

ylacaute commented 7 years ago

@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 commented 7 years ago

@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();
};
jai18881 commented 7 years ago

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.

RyanThomas95 commented 6 years ago

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

inmchfw commented 6 years ago

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

KNeela commented 6 years ago

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

kptcs commented 6 years ago

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,

alexkreidler commented 6 years ago

Any updates?

dharaghodasara commented 5 years ago

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

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

mabihan commented 5 years ago

Using @ChrisShen93 and @snecker tips I made this example : https://github.com/JeanReneRobin/json-server-multiple-files