Last active
January 18, 2022 05:59
-
-
Save daffl/259f005ea38bc744d02d80b5a28e2b11 to your computer and use it in GitHub Desktop.
New Feathers service hooks TypeScript decorator example
This file contains hidden or 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, NextFunction } from '@feathersjs/hooks' | |
import { authenticate } from '@feathersjs/authentication' | |
import { HookContext } from './declarations' | |
const logRuntime = async (context: HookContext, next: NextFunction) => { | |
const start = Date.now() | |
// Pass to the next hooks in the chain and the service method | |
await next() | |
// Log the total runtime | |
console.log(`${context.path}.${context.method} took ${Date.now() - start}ms`) | |
} | |
const exclaim = async (context: HookContext, next: NextFunction) => { | |
// Run all other hooks and the service method first | |
await next() | |
// Update the result with an updated message | |
context.result = { | |
message: `${context.result.message}!!!` | |
} | |
} | |
// Hooks that run on all service methods | |
@hooks([ | |
authenticate('jwt'), | |
logRuntime | |
]) | |
export class MyService { | |
// Hooks that only run for this method | |
@hooks([ exclaim ]) | |
async get (name: string) { | |
return { | |
message: `Hello ${name}` | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment