Skip to content

Instantly share code, notes, and snippets.

@gavinmcfarland
Created April 20, 2020 14:26
Show Gist options
  • Save gavinmcfarland/faa784c237a011f0e003772ca11ce0e9 to your computer and use it in GitHub Desktop.
Save gavinmcfarland/faa784c237a011f0e003772ca11ce0e9 to your computer and use it in GitHub Desktop.
Middlewear for json-server
// 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()
}
// 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