Giter Club home page Giter Club logo

Comments (21)

typicode avatar typicode commented on September 12, 2024 12

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.

ChrisShen93 avatar ChrisShen93 commented on September 12, 2024 11

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

kptcs avatar kptcs commented on September 12, 2024 9

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.

snecker avatar snecker commented on September 12, 2024 7

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.

typicode avatar typicode commented on September 12, 2024 6

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.

alexkreidler avatar alexkreidler commented on September 12, 2024 4

Any updates?

from json-server.

mabihan avatar mabihan commented on September 12, 2024 4

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

from json-server.

gagan-bansal avatar gagan-bansal commented on September 12, 2024 3

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

from json-server.

dharaghodasara avatar dharaghodasara commented on September 12, 2024 2

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

altano avatar altano commented on September 12, 2024 1

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.

Celestz avatar Celestz commented on September 12, 2024

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.

yesarpit avatar yesarpit commented on September 12, 2024

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.

mcolomerc avatar mcolomerc commented on September 12, 2024

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.

ylacaute avatar ylacaute commented on September 12, 2024

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

ChrisShen93 avatar ChrisShen93 commented on September 12, 2024

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

from json-server.

ylacaute avatar ylacaute commented on September 12, 2024

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

ylacaute avatar ylacaute commented on September 12, 2024

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

jai18881 avatar jai18881 commented on September 12, 2024

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.

RyanThomas95 avatar RyanThomas95 commented on September 12, 2024

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

inmchfw avatar inmchfw commented on September 12, 2024

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.

KNeela avatar KNeela commented on September 12, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.