How to use the json-server.rewriter 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 benc-uk / smilr / vue / mock-api / server.js View on Github external
// Set up middleware and bodyParser for JSON
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)

// Static routes
server.get('/api', (req, res) => {
  res.send('<h1>Mock API server for Smilr is running</h1>')
})
server.get('/api/info', (req, res) =&gt; {
  res.send({ message: "Mock API server for Smilr is running"})
})

// Various routes and tricks to act like the real Smilr API
var today = new Date().toISOString().substr(0, 10)
server.use(jsonServer.rewriter({
  "/api/feedback/:eid/:tid":    "/api/feedback?event=:eid&amp;topic=:tid",
  "/api/events/filter/future":  "/api/events?start_gte="+today+"&amp;start_ne="+today,
  "/api/events/filter/past":    "/api/events?end_lte="+today+"&amp;start_ne="+today,
  "/api/events/filter/active":  "/api/events?start_lte="+today+"&amp;end_gte="+today
}))

// Fake real network with a slight random delay
server.use('/api', function(req, res, next) {
  setTimeout(next, Math.random()*1500)
})

// Set the main router up
server.use('/api', router)

// Start the server on port 4000
server.listen(4000, () =&gt; {
github NationalBankBelgium / stark / packages / stark-build / config / json-server.common.js View on Github external
var router = jsonServer.router(data);
	var defaultMiddlewares = jsonServer.defaults({ bodyParser: false }); // disable default bodyParser usage since it causes some issues

	// set ExpressJS App settings
	// http://expressjs.com/en/api.html#app.settings.table
	server.set("etag", false); // disable default etag generation

	router.db._.id = "uuid"; // use "uuid" as resource id

	routes = routes || {};
	var starkRoutes = {};
	// merge routes into starkRoutes
	Object.assign(starkRoutes, routes);
	starkRoutes = expandRewrittenRoutes(starkRoutes);

	server.use(jsonServer.rewriter(starkRoutes));
	server.use(defaultMiddlewares);
	// use bodyParser separately passing the same options as in json-server defaults
	server.use(bodyParser.json({ limit: "10mb", extended: false }));
	server.use(bodyParser.urlencoded({ extended: false }));
	server.use(transformRequests);

	if (uploadEndpoints && uploadEndpoints instanceof Array) {
		addUploadEndpoints(server, uploadEndpoints);
	}

	// Apply custom request transformations (if any)
	middlewares = middlewares || {};
	if (middlewares.transformRequests) {
		server.use(middlewares.transformRequests);
	}
github mike-north / ember-octane-workshop / server / api-server.js View on Github external
};
    next();
  }

  server.use('/api', SINGULAR_MIDDLEWARE, ...middlewares);

  server.use(jsonServer.bodyParser);
  server.use((req, _res, next) => {
    if (req.method === 'POST') {
      req.body.createdAt = Date.now();
    }
    // Continue to JSON Server router
    next();
  });
  server.use(
    jsonServer.rewriter({
      '/api/teams/:id': '/api/teams/:id?_embed=channels',
      '/api/teams/:id/channels': '/api/channels?teamId=:id',
      '/api/teams/:id/channels/:channelId':
        '/api/channels?id=:channelId&teamId=:id&singular=1',
      '/api/teams/:id/channels/:channelId/messages':
        '/api/messages?_expand=user&teamId=:id&channelId=:channelId',
    })
  );

  server.use('/api', router);
  return server;
};
github alephdata / aleph / ui / mocks / server.js View on Github external
res.jsonp({
      "total": results.length,
      "page": 1,
      "offset": 0,
      "limit": 25,
      "pages": 223830,
      results: results
    })
  } else {
    res.jsonp(res.locals.data);
  }
}

server.use(middlewares)
server.use(pause(500))
server.use(jsonServer.rewriter({
  '/api/': '/'
}))
server.use(router)
server.listen(3001, () => {
  console.log('JSON Server is running')
})
github YerevaNN / dmn-ui / server / index.js View on Github external
'use strict';

const factsN    = 10;
const episodesN = 5;

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

const server = jsonServer.create();

server.use(jsonServer.defaults({
  static: './dist'
}));

const router   = jsonServer.router('./server/db.json');
const rewriter = jsonServer.rewriter(require('./routes.json'));


function getAttention() {
  return Math.round(Math.random() * 100) / 100;
}

server.use(rewriter);

server.post('/networks/:network/models/:model/_predict', (req, res) => {
  const db = router.db.object;

  const prediction = {
    answer: db.vocab[Math.floor(Math.random() * db.vocab.length)],
    confidence: Math.random(),
    facts: [],
    episodes: []
github ManageIQ / manageiq-ui-service / mock_api / server.js View on Github external
function startServer() {
  server.use(jsonServer.rewriter({
    '/api/:resource': '/:resource',
  }));

  server.use(middlewares);
  server.use(function(req, res) {
    res.sendStatus(501);
  });
  server.use(router);

  let port = 3000;
  if (process.env.MOCK_API_HOST) {
    let urlParts = url.parse(process.env.MOCK_API_HOST, false);
    port = urlParts.host;
  }

  server.listen(port, function() {
github jeremyben / json-server-auth / src / guards.ts View on Github external
export function rewriter(resourceGuardMap: { [resource: string]: number }): Router {
	const routes = parseGuardsRules(resourceGuardMap)
	return jsonServer.rewriter(routes)
}
github TommyCpp / Athena / frontend / web / src / mockend / mockend.js View on Github external
/*
* Be advised that this mockend is not for unit test or e2e test. It is for demo representation only.
* */
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
server.use(jsonServer.rewriter({
  "/book/:id": "/book?isbn=:id"
}));

const readers = {
  11: "12314",
  12: "12234"
};

const admins = {
  16: "1111"
};

const superAdmins = {
  10: "11111"
};
github lechatquidanse / bicing-user-interface-app / docker / development / mock / server.js View on Github external
const https = require('https');
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const jsonServer = require('json-server');

const routesFilePath = path.join(__dirname, '/custom/routes.json');
let rewriter;
if (fs.existsSync(routesFilePath)) {
  const routes = fs.readFileSync(routesFilePath);
  rewriter = jsonServer.rewriter(JSON.parse(routes));
}

let db = JSON.parse(fs.readFileSync(path.join(__dirname, '/custom/db.json')));
const customDbPath = path.join(__dirname, '/custom/custom-db.json');

if (fs.existsSync(customDbPath)) {
  const customDb = JSON.parse(fs.readFileSync(customDbPath));
  _.mergeWith(db, customDb, (obj, src) => {
    if (_.isArray(obj)) {
      return obj.concat(src);
    }
  });
}

const router = jsonServer.router(db);
router.render = function (req, res) {

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 3 months ago

Package Health Score

86 / 100
Full package analysis