Created
January 14, 2020 16:29
-
-
Save daffl/faf16431760ce5dfa5d50c337a374c8d to your computer and use it in GitHub Desktop.
Async middleware with TypeScript
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 { hooks, HookContext, NextFunction } from '@feathersjs/hooks'; | |
const logRuntime = async (context: HookContext, next: NextFunction) => { | |
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: HookContext, next: NextFunction) => { | |
const [ name ] = context.arguments; | |
if (!name || name.trim() === '') { | |
throw new Error('Name is not valid'); | |
} | |
// Always has to be called | |
await next(); | |
} | |
class Hello { | |
@hooks([ | |
logRuntime, | |
validateName | |
]) | |
async sayHi (name: string) { | |
return `Hi ${name}`; | |
} | |
} | |
(async () => { | |
const hi = new Hello(); | |
console.log(await hi.sayHi('David')); | |
// The following would throw an error | |
// console.log(await hi.sayHi(' ')); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment