Can generate random data based on parameters?
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?
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
somethingas a key in yourdb.jsonfile
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.
I now have this tool to simplify these operations, including static files, automatic updates, CORS...
module.exports = util => {
return {
db: util.libObj.mockjs.mock({
'users|15-23': [ // Randomly generate 15 to 23 data
{
'id|+1': 1, // id increments from 1
name: `@cname`, // Randomly generate Chinese name
'sex|1': [`male`, `female`, `secret`], // Gender randomly choose one from these three options
},
]
}),
}
}