Created
March 15, 2017 18:12
-
-
Save mateomurphy/84947c0d00b22948635e092e0393913b to your computer and use it in GitHub Desktop.
middleware for https://github.com/twg/devour
This file contains 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
import _ from 'lodash' | |
function deepMapKeys(obj, fn) { | |
if (_.isArray(obj)) { | |
return _.map(obj, (v) => deepMapKeys(v, fn)) | |
} | |
if (_.isPlainObject(obj)) { | |
let newObj = {} | |
_.forOwn(obj, (v, k) => { | |
newObj[fn(k)] = deepMapKeys(v, fn) | |
}) | |
return newObj | |
} | |
return obj | |
} | |
export const errorMiddleware = { | |
name: 'pass-errors-through', | |
error: function (payload) { | |
return payload.data.errors | |
} | |
} | |
export const camelCaseMiddleware = { | |
name: 'camel-case-response', | |
res: (payload) => { | |
if (payload.res.data) { | |
payload.res.data = deepMapKeys(payload.res.data, _.camelCase) | |
} | |
return payload | |
} | |
} | |
export const kebabCaseMiddleware = { | |
name: 'kebab-case-request', | |
req: function (payload) { | |
if (payload.req.data) { | |
payload.req.data = deepMapKeys(payload.req.data, _.kebabCase) | |
} | |
return payload | |
} | |
} | |
// usage | |
client.replaceMiddleware('errors', errorMiddleware) | |
client.insertMiddlewareBefore('axios-request', kebabCaseMiddleware) | |
client.insertMiddlewareBefore('response', camelCaseMiddleware) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment