Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Last active February 16, 2018 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xjamundx/a25fc4c4463ed64c9abfbdc9208e43ea to your computer and use it in GitHub Desktop.
Save xjamundx/a25fc4c4463ed64c9abfbdc9208e43ea to your computer and use it in GitHub Desktop.
// idea 1 - use JOI (or similar) at the router level
let params = {
query: {
limit: Joi.number().integer().min(1).max(100).default(10)
}
}
server.get("/horse", enforceParams(params), controller.myRoute)
// idea 2 - use JOI (or similar) at the controller level
async function myRoute(req, res) {
let params = {
query: {
accountId: Joi.string(),
limit: Joi.number().integer().min(1).max(100).default(10)
}
}
enforceParams(req, params)
/* ... other stuff ... */
}
// idea 3 - manually using a custom Error object
async function myRoute(req, res) {
if (!req.params.accountId) {
throw new MissingParamError("Missing required accountId")
}
if (typeof req.query.limit !== 'number') {
throw new MissingParamError("Expected limit to be a number")
}
/* ... other stuff ... */
}
// idea 4 - decorators
@params({
query: {
accountId: Joi.string(),
limit: Joi.number().integer().min(1).max(100).default(10)
}
})
function myRoute(req, res) {}
// idea 5 - use flow, but then transpile with a plugin to convert to somethign like 3?
async function myRoute(req, res) {
let params: { limit?: number, accountId: string } = req.params
}
// converts with a babel plugin to
async function myRoute(req, res) {
let params = req.params
if (typeof params.accountId !== 'string') {
throw new MissingParamError("accountId must be a string")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment