Created
August 19, 2020 11:31
-
-
Save Sande3p/6cfbbf7f46c1d081a17bed3880cfd37c to your computer and use it in GitHub Desktop.
Mock API sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const jsonServer = require('json-server'); | |
const express = require('express'); | |
const path = require('path'); | |
const enableDestroy = require('server-destroy'); | |
const PORT = process.env.PORT || 3000; | |
const MOCK_JWT = 'eyJhbGciOiJIUzUxMiJ9.eyJGUG0T42kApIiGnA'; | |
// Preprocess db.json | |
const DB_JSON_PATH = 'db/db.json'; | |
let app = undefined; | |
function startServer() { | |
const server = jsonServer.create(); | |
const router = jsonServer.router(DB_JSON_PATH); | |
const request = require('request'); | |
const middlewares = jsonServer.defaults(); | |
Array.prototype.randomChoice = function () { | |
const length = this.length; | |
const index = Math.floor(Math.random() * length); | |
return this[index]; | |
}; | |
server.use(middlewares); | |
server.use(jsonServer.bodyParser); | |
server.use('/static', express.static(path.join(__dirname, 'public'))); | |
// Custom routes | |
const routes = JSON.parse(fs.readFileSync('routes.json')); | |
server.use(jsonServer.rewriter(routes)); | |
function isAuthorized(req) { | |
return req.headers.jwt === MOCK_JWT; | |
} | |
// GET /tasks | |
function shouldReturnObjectForTasks(reqQuery) { | |
return (reqQuery.type === 'OPAM' && reqQuery.id !== undefined) | |
|| (reqQuery.type === 'Field' && reqQuery.taskId !== undefined); | |
} | |
// GET /equipments | |
function shouldReturnObjectForEquipments(reqQuery) { | |
return reqQuery.equipmentId !== undefined; | |
} | |
// GET /permits | |
function shouldReturnObjectForPermits(reqQuery) { | |
return reqQuery.workRequestName !== undefined; | |
} | |
const SHOULD_RETURN_OBJECT_CHECKER_HANDLERS = { | |
'/permits': shouldReturnObjectForPermits, | |
'/equipments': shouldReturnObjectForEquipments, | |
'/tasks': shouldReturnObjectForTasks, | |
} | |
// Access control | |
server.use((req, res, next) => { | |
if (isAuthorized(req)) { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); | |
const original = res.send; | |
const host = req.get('host'); | |
const protocol = req.protocol; | |
res.send = (jsonDataStr) => { | |
// Replace the placeholder of the meida URL. | |
if (jsonDataStr && typeof(jsonDataStr) === 'string') { | |
jsonDataStr = jsonDataStr.replace(/\{\{HOST_PLACEHOLDER\}\}/g, `${protocol}://${host}`); | |
} | |
const checkerHandler = SHOULD_RETURN_OBJECT_CHECKER_HANDLERS[req.path] | |
if (checkerHandler && checkerHandler(req.query)) { | |
// Check if the query param contains id, and response data is a an array and only contain one element | |
// If so, just return a JSON object. | |
try { | |
let jsonData = JSON.parse(jsonDataStr); | |
if (Array.isArray(jsonData) && jsonData.length === 1) { | |
jsonData = jsonData[0]; | |
jsonDataStr = JSON.stringify(jsonData) | |
} | |
} catch (e) { | |
console.error(e); | |
} | |
} | |
return original.call(res, jsonDataStr); | |
}; | |
next(); | |
} else { | |
// res.statusMessage = 'Unauthorized access'; | |
// res.sendStatus(401); | |
res.writeHead(401, { | |
'Content-Type': 'application/json' | |
}); | |
res.write(JSON.stringify({ | |
message: 'Unauthorized access' | |
})); | |
res.end(); | |
} | |
}); | |
server.post('/PostReq', (req, res) => { | |
const host = req.get('host'); | |
const protocol = req.protocol; | |
const url = `${protocol}://${host}/equipments?equipmentTag=P6429`; | |
const options = { | |
url, | |
json: true, | |
method: 'GET', | |
headers: { | |
Accept: 'application/json', | |
jwt: MOCK_JWT, | |
}, | |
}; | |
request(options, (_2, _3, body) => { | |
res.send(body); | |
}); | |
}); | |
server.use(router); | |
app = server.listen(PORT, ()=>{ | |
const addressInfo = app.address(); | |
console.log(`http://${addressInfo.address}:${addressInfo.port} Running`); | |
}); | |
enableDestroy(app); // Display server informations | |
} | |
startServer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment