How to use the json-server.defaults function in json-server

To help you get started, we’ve selected a few json-server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ManageIQ / manageiq-ui-service / mock_api / server.js View on Github external
const jsonServer = require('json-server');
const fs = require('fs');
const url = require('url');
const lodash = require('lodash');
const glob = require('glob');
const path = require('path');

let server = jsonServer.create();
let router = jsonServer.router();
let middlewares = jsonServer.defaults();

init();

function init() {
  server.use(jsonServer.bodyParser);
  server.use(function(req, res, next) {
    if (process.env.LOG_LEVEL && process.env.LOG_LEVEL === 'debug') {
      console.log(req.body);
    }
    next();
  });

  loadDataFiles().then(function(resp) { // We load all endpoints
    return loadLocalOverrideFiles(resp);
  })
    .then(function(endpoints) { // We apply local endpoint overrides
github robeio / robe-react-ui / ConfigUtil.js View on Github external
config.createJsonServer = (port, routePath, uploadContextPath, tempFolder) => {
    // server.js

    const server = jsonServer.create();
    const router = jsonServer.router(routePath);
    const middlewares = jsonServer.defaults();

    if (!tempFolder) {
        tempFolder = "temp";
    }

    tempFolder = path.join(__dirname, tempFolder);
    // const upload = fileSaver(tempFolder);
    //  server.post(tempRequestPath, (req, res) => {
    //     res.send({ responseText: req.file.path });
    // });
    /*
     const upload = fileSaver(tempFolder);
    server.post("/files", upload.any(), (req, res) => {
        console.log("Example file completed...");
        res.sendStatus(200);
    });
github Capgemini / mesos-ui / src / server.js View on Github external
require('./routes/zookeeper')(app);
} else if (process.env.MESOS_ENDPOINT) {
  require('./routes/dev')(app);
}

// If we're in development mode spin up a mock server as we may not have a
// running Mesos cluster, so lets just use the stub API in ./stub.json.
if (process.env.NODE_ENV === 'development') {
  let jsonServer = require('json-server');
  let fs = require('fs');

  // Returns an Express server
  let server = jsonServer.create();

  // Set default middlewares (logger, static, cors and no-cache)
  server.use(jsonServer.defaults());

  const stubFile = './src/stub.json';
  let router = jsonServer.router(stubFile);
  server.use(router);

  server.listen(8000);
}
github magma / magma / nms / app / fbcnms-projects / magmalte / scripts / mockServer.js View on Github external
* limitations under the License.
 *
 * @flow
 * @format
 */

const jsonServer = require('json-server');
const https = require('https');
const fs = require('fs');

const keyFile = 'mock/.cache/mock_server.key';
const certFile = 'mock/.cache/mock_server.cert';

const server = jsonServer.create();
const router = jsonServer.router('mock/db.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);

const buffer = fs.readFileSync('mock/db.json', 'utf-8');
const db = JSON.parse(buffer);

// add custom route handlers
server.get('/magma/v1/networks/test/gateways', (req, res) => {
  if (req.method === 'GET') {
    res.status(200).jsonp(db['networksFull']['test']['gateways']);
  }
});

server.get('/magma/v1/networks/test/type', (req, res) => {
  if (req.method === 'GET') {
    res.status(200).jsonp(db['networksFull']['test']['type']);
  }
github zce / dashboard-server / lib / index.js View on Github external
getToken: token.getToken,
  isRevoked: (req, payload, done) => done(null, data.isRevokedToken(payload))
})

// Role authorize
const roleAuthorize = (req, res, next) => {
  if (!req.user) return res.status(401).send({ message: 'Requires authentication.' })

  // TODO: delete token or logout
  const user = data.getUserBySlug(req.user.slug)
  if (user.roles.includes('administrator')) return next()
  res.status(403).send({ message: 'Requires administrator.' })
}

// Common middlewares
server.use(jsonServer.defaults())
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
  // enable?
  if (!config.enableDelay) return next()
  // ignore options request
  if (req.method === 'OPTIONS') return next()
  setTimeout(next, Math.random() * 1000)
})

// backdoor: Toggle delay action
server.get('/backdoor/delay', (req, res) => {
  config.enableDelay = !config.enableDelay
  res.send(config.enableDelay)
})

// backdoor: Reset database
github bucharest-gold / roi / test / fake-server.js View on Github external
static create (port) {
    const server = jsonServer.create();
    const router = jsonServer.router(this.createDb());
    server.use(jsonServer.defaults());
    server.use(router);
    const s = server.listen(port);
    return s;
  }
}
github themzed / PersianJSONPlaceholder / src / app.js View on Github external
const { ApolloServer, gql } = require('apollo-server-express');

const data = require('../data.json')

const app = jsonServer.create()
const router = jsonServer.router(clone(data), {
  _isFake: true
})

app.use((req, res, next) => {
  if (req.path === '/') return next()
  router.db.setState(clone(data))
  next()
})

app.use(jsonServer.defaults({
  logger: process.env.NODE_ENV !== 'production'
}))

app.use(router)

module.exports = app
github actum / gulp-dev-stack / gulp / tasks / api.js View on Github external
function start() {
  const api = requireUncached('../../src/api/api');
  const app = jsonServer.create();
  const router = jsonServer.router(api());
  const middleware = jsonServer.defaults();
  app.use(middleware);
  app.use(router);
  server = app.listen(config.API_PORT, () => {
    gutil.log(
      gutil.colors.green('JSON Server is running…'),
      gutil.colors.gray(`http://localhost:${config.API_PORT}`),
    );
  });
  enableDestroy(server);
}
github mjzhang1993 / react-router4-template / server / index.js View on Github external
const jsonServer = require('json-server');
const ip = require('ip').address();
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const createDB = require('./db.js');
const mounted = require('./route');
const DB = createDB();
const router = jsonServer.router(DB);

server.use(jsonServer.bodyParser);
server.use(middlewares);

mounted(server, DB);
server.use(router);

server.listen(
   {
      host: ip,
      port: 3167
   },
github pharindoko / json-serverless / src / core.js View on Github external
function startLocal(db) {
  logger.info('start locals environment');
  const router = jsonServer.router(db);
  const middlewares = jsonServer.defaults({ readOnly: appConfig.readOnly });
  setupServer(middlewares, router, db);
}

json-server

[![Node.js CI](https://github.com/typicode/json-server/actions/workflows/node.js.yml/badge.svg)](https://github.com/typicode/json-server/actions/workflows/node.js.yml)

SEE LICENSE IN ./LICENSE
Latest version published 2 months ago

Package Health Score

85 / 100
Full package analysis