Skip to content

Instantly share code, notes, and snippets.

@reggi
Last active July 12, 2017 19:32
Show Gist options
  • Select an option

  • Save reggi/163cded1d9280f648fa6245828bea627 to your computer and use it in GitHub Desktop.

Select an option

Save reggi/163cded1d9280f648fa6245828bea627 to your computer and use it in GitHub Desktop.
/*
Here's a bit of code demonstrating the cascade of usign `static` functions within a class.
From top to bottom each subsiquent function utilizes the next. This allows you to piece-meal
the functions needed by declaring the method names based on what they return i.e. `bool`, `throw`, and `middleware`.
Note, I'm intentionally not using a constructor here, and I am also intentionally passing in
the same arguments to each of the function methods.
*/
class ValidateBody {
static errorMessage = 'invalid body'
static errorCode = '123'
static Error = Error
static bool (body) {
if (!body) return false
if (!body.header) return false
if (!body.header.data) return false
return true
}
static error (body) {
if (!ValidateBody.bool(body)) {
return new ValidateBody.Error(`${ValidateBody.errorCode}: ${ValidateBody.errorMessage}`)
}
return null
}
static throw (body) {
const result = ValidateBody.error(body)
if (result instanceof Error) {
throw ValidateBody.error(body)
}
return null
}
static middleware () {
return (req, res, next) => {
return next(ValidateBody.thrower(req.body))
}
}
}
console.log(ValidateBody.bool({}))
console.log(ValidateBody.throw({}))
console.log(ValidateBody.middleware({})())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment