Json-server: Can generate random data based on parameters?

Created on 8 Dec 2016  路  2Comments  路  Source: typicode/json-server

For instance:

The url is: localhost:3000/something?min=20161201&max=20161208
The result is:

{ date: [20161201, 20161202, 20161203, 20161204, 20161205, 20161206, 20161207, 20161208] }

Could we do that?

Most helpful comment

Hi Snowffer,

Although this might be unrelated to json-server but I hope the below helps you to understand how to accomplish your goal in different ways

I've created a quick github repository for answering this question accurately, feel free to use it or refer to the below code snippets which is nothing other than copies from this repo files

General Assumptions

  • only one parameter required (either min or max)
  • default for min if not send is 1
  • default for max if not send is 90000000

Solution 1 (using http server)

If you don't use any json-server capabilities then you shouldn't do this simple task with it as this will be over engineering it. instead, you could do a simple and super lite http server and put your logic

Solution 1 assumptions

  • you only need this single endpoint to accomplish your orverall task
const http = require('http');
const url = require('url');
const pathPattern = /\/something\/?$/;

const PORT = 3000;

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}

function sendResponse(response, status, json) {
  response.writeHead(status, {'Content-Type': 'text/json'});
  response.end(JSON.stringify(json));
}

function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;

  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}

function randomizeMiddleware(req, res) {

  let requestUrl = url.parse(req.url, true);
  let query = requestUrl.query
  let requestedPath = requestUrl.pathname;

  if (requestedPath.match(pathPattern)) {

    if (query.min || query.max) {

      let randomArray = generateRandomArray(query.min, query.max);

      sendResponse(res, 200, randomArray);

    } else {
      sendResponse(res, 400, {
        "error": "you should at least send one of min or max as query string"
      });
    }
  } else {
    sendResponse(res, 404, {
      "error": "can't find what you are looking for"
    });
  }
}

var server = http.createServer(randomizeMiddleware);

server.listen(PORT, function () {
  console.log("Server listening on: http://localhost:%s", PORT);
});

Solution 1 Pros

  • super lite

Solution 1 Cons

  • hard to maintain and add other endpoints

Solution 2 (using express server)

This Solution is using http://expressjs.com/ server with all of its powerful capabilities

#### Solution 2 assumptions

  • you still want to implement this along with some other endpoints that doesn't really need json-server module
var express = require('express');
var app = express();

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}
function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;
  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}
function randomizeMiddleware(req, res) {
  if (req.query.min || req.query.max) {

    let randomArray = generateRandomArray(req.query.min, req.query.max);

    res.send(randomArray);

  } else {
    res.status(400).send({
      "error": "you should at least send one of min or max as query string"
    })
  }
}

app.use('/something', randomizeMiddleware)

app.use(function (req, res) {
  res.status(404).send({
    "error": "can't find what you are looking for"
  })
})

app.listen(3000, function () {
  console.log('app is running in port 3000');
})

Solution 2 Pros

  • flexibility (you can easily add other endpoints)
  • maintainability (easier to maintain and you don't have to care about/handle http url parsing, query strings, methods .. etc)

Solution 2 Cons

  • if you don't build an application with other different endpoint, it is overwhelming
  • require some expressjs knowledge

Solution 3 (using json-server)

This Solution is using json-server as a module (not CLI) with all of its powerful capabilities which (considering only your provided example) is not needed, however:

#### Solution 3 assumptions

  • you still want to implement this along with some other endpoints that DOES need json-server cababilities and you want to add this logic to it
  • you don't use something as a key in your db.json file
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()

server.use(middlewares)

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}
function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;
  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}
function randomizeMiddleware(req, res) {
  if (req.query.min || req.query.max) {

    let randomArray = generateRandomArray(req.query.min, req.query.max);

    res.send(randomArray);

  } else {
    res.status(400).send({
      "error": "you should at least send one of min or max as query string"
    })
  }
}


server.use('/something', randomizeMiddleware)
server.use(router)

server.use(function (req, res) {
  res.status(404).send({
    "error": "can't find what you are looking for"
  })
})

server.listen(3000, function () {
  console.log('JSON Server is running')
})

Solution 3 Pros

  • flexibility (you can easily add other endpoints)
  • maintainability (easier to maintain and you don't have to care about/handle http url parsing, query strings, methods .. etc)

Solution 3 Cons

  • if you don't build an application with other different endpoints, it is still overwhelming
  • require some expressjs + json-server advanced knowledge

in conclusion, you should only use as much as you need from any library and if you don't use at least 30% of its capabilities then consider other options.

Please let me know if you need further clarifications.

All 2 comments

Hi Snowffer,

Although this might be unrelated to json-server but I hope the below helps you to understand how to accomplish your goal in different ways

I've created a quick github repository for answering this question accurately, feel free to use it or refer to the below code snippets which is nothing other than copies from this repo files

General Assumptions

  • only one parameter required (either min or max)
  • default for min if not send is 1
  • default for max if not send is 90000000

Solution 1 (using http server)

If you don't use any json-server capabilities then you shouldn't do this simple task with it as this will be over engineering it. instead, you could do a simple and super lite http server and put your logic

Solution 1 assumptions

  • you only need this single endpoint to accomplish your orverall task
const http = require('http');
const url = require('url');
const pathPattern = /\/something\/?$/;

const PORT = 3000;

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}

function sendResponse(response, status, json) {
  response.writeHead(status, {'Content-Type': 'text/json'});
  response.end(JSON.stringify(json));
}

function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;

  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}

function randomizeMiddleware(req, res) {

  let requestUrl = url.parse(req.url, true);
  let query = requestUrl.query
  let requestedPath = requestUrl.pathname;

  if (requestedPath.match(pathPattern)) {

    if (query.min || query.max) {

      let randomArray = generateRandomArray(query.min, query.max);

      sendResponse(res, 200, randomArray);

    } else {
      sendResponse(res, 400, {
        "error": "you should at least send one of min or max as query string"
      });
    }
  } else {
    sendResponse(res, 404, {
      "error": "can't find what you are looking for"
    });
  }
}

var server = http.createServer(randomizeMiddleware);

server.listen(PORT, function () {
  console.log("Server listening on: http://localhost:%s", PORT);
});

Solution 1 Pros

  • super lite

Solution 1 Cons

  • hard to maintain and add other endpoints

Solution 2 (using express server)

This Solution is using http://expressjs.com/ server with all of its powerful capabilities

#### Solution 2 assumptions

  • you still want to implement this along with some other endpoints that doesn't really need json-server module
var express = require('express');
var app = express();

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}
function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;
  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}
function randomizeMiddleware(req, res) {
  if (req.query.min || req.query.max) {

    let randomArray = generateRandomArray(req.query.min, req.query.max);

    res.send(randomArray);

  } else {
    res.status(400).send({
      "error": "you should at least send one of min or max as query string"
    })
  }
}

app.use('/something', randomizeMiddleware)

app.use(function (req, res) {
  res.status(404).send({
    "error": "can't find what you are looking for"
  })
})

app.listen(3000, function () {
  console.log('app is running in port 3000');
})

Solution 2 Pros

  • flexibility (you can easily add other endpoints)
  • maintainability (easier to maintain and you don't have to care about/handle http url parsing, query strings, methods .. etc)

Solution 2 Cons

  • if you don't build an application with other different endpoint, it is overwhelming
  • require some expressjs knowledge

Solution 3 (using json-server)

This Solution is using json-server as a module (not CLI) with all of its powerful capabilities which (considering only your provided example) is not needed, however:

#### Solution 3 assumptions

  • you still want to implement this along with some other endpoints that DOES need json-server cababilities and you want to add this logic to it
  • you don't use something as a key in your db.json file
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()

server.use(middlewares)

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}
function generateRandomBetween(min, max) {
  if (isNumeric(min) && isNumeric(max)) {
    return Math.floor(Math.random() * parseFloat(max)) + parseFloat(min)
  }
}
function generateRandomArray(min, max) {

  min = min || 1;
  max = max || 90000000;
  let maxArrayLength = generateRandomBetween(1, 20);
  let randomArray = [];

  for (var i = 0; i < maxArrayLength; i++) {
    randomArray.push(generateRandomBetween(min, max))
  }

  return randomArray
}
function randomizeMiddleware(req, res) {
  if (req.query.min || req.query.max) {

    let randomArray = generateRandomArray(req.query.min, req.query.max);

    res.send(randomArray);

  } else {
    res.status(400).send({
      "error": "you should at least send one of min or max as query string"
    })
  }
}


server.use('/something', randomizeMiddleware)
server.use(router)

server.use(function (req, res) {
  res.status(404).send({
    "error": "can't find what you are looking for"
  })
})

server.listen(3000, function () {
  console.log('JSON Server is running')
})

Solution 3 Pros

  • flexibility (you can easily add other endpoints)
  • maintainability (easier to maintain and you don't have to care about/handle http url parsing, query strings, methods .. etc)

Solution 3 Cons

  • if you don't build an application with other different endpoints, it is still overwhelming
  • require some expressjs + json-server advanced knowledge

in conclusion, you should only use as much as you need from any library and if you don't use at least 30% of its capabilities then consider other options.

Please let me know if you need further clarifications.

@Nilegfx Thx for the details and sorry for so late to reponse.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TXRRNT picture TXRRNT  路  4Comments

fishenal picture fishenal  路  3Comments

pantchox picture pantchox  路  3Comments

casvil picture casvil  路  4Comments

melnikovic picture melnikovic  路  3Comments