Created
January 14, 2020 16:28
-
-
Save daffl/a94c58916bfd47d565e90d7e8e9809d4 to your computer and use it in GitHub Desktop.
Async middleware with JavaScript
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
const { hooks } = require('@feathersjs/hooks'); | |
const logRuntime = async (context, next) => { | |
const start = new Date().getTime(); | |
await next(); | |
const end = new Date().getTime(); | |
console.log(`Function '${context.method || '[no name]'}' returned '${context.result}' after ${end - start}ms`); | |
} | |
const validateName = async (context, next) => { | |
const [ name ] = context.arguments; | |
if (!name || name.trim() === '') { | |
throw new Error('Name is not valid'); | |
} | |
// Always has to be called | |
await next(); | |
} | |
// Hooks can be used with a function like this: | |
const sayHello = hooks(async name => { | |
return `Hello ${name}!`; | |
}, [ | |
logRuntime, | |
validateName | |
]); | |
// And on an object or class like this | |
class Hello { | |
async sayHi (name) { | |
return `Hi ${name}` | |
} | |
} | |
hooks(Hello, { | |
sayHi: [ | |
logRuntime, | |
validateName | |
] | |
}); | |
(async () => { | |
console.log(await sayHello('David')); | |
// The following would throw an error | |
// await sayHello(' '); | |
const hi = new Hello(); | |
console.log(await hi.sayHi('Dave')); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment