Created
April 20, 2020 14:26
-
-
Save gavinmcfarland/faa784c237a011f0e003772ca11ce0e9 to your computer and use it in GitHub Desktop.
Middlewear for json-server
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
// Returns the value of a field/key. | |
// Add field=:field to url query | |
module.exports = (req, res, next) => { | |
const _send = res.send | |
res.send = function (body) { | |
let field = require('url').parse(req.url, true).query['_field'] | |
if (field) { | |
try { | |
const json = JSON.parse(body) | |
if (Array.isArray(json)) { | |
if (json.length === 1) { | |
return _send.call(this, JSON.stringify(json[0][field], null, ' ')) | |
} else if (json.length === 0) { | |
return _send.call(this, '{}', 404) | |
} | |
} | |
} catch (e) { } | |
} | |
return _send.call(this, body) | |
} | |
next() | |
} |
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
// Returns an object if only one item in array | |
// Add singular=1 to url query | |
module.exports = (req, res, next) => { | |
const _send = res.send | |
res.send = function (body) { | |
if (require('url').parse(req.url, true).query['singular']) { | |
try { | |
const json = JSON.parse(body) | |
if (Array.isArray(json)) { | |
if (json.length === 1) { | |
return _send.call(this, JSON.stringify(json[0], null, ' ')) | |
} else if (json.length === 0) { | |
return _send.call(this, '{}', 404) | |
} | |
} | |
} catch (e) { } | |
} | |
return _send.call(this, body) | |
} | |
next() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment