Skip to content

Instantly share code, notes, and snippets.

@daffl
Created January 14, 2020 16:29
Show Gist options
  • Save daffl/faf16431760ce5dfa5d50c337a374c8d to your computer and use it in GitHub Desktop.
Save daffl/faf16431760ce5dfa5d50c337a374c8d to your computer and use it in GitHub Desktop.
Async middleware with TypeScript
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