-
I've have custom service methods working, but now I'm trying to figure out how to attach hooks to them. If I try to add the custom method's name to the hooks file generated by the CLI, I get an error: How should hooks be attached to custom methods? |
Beta Was this translation helpful? Give feedback.
Answered by
daffl
Jun 14, 2021
Replies: 1 comment 4 replies
-
Custom methods only work with the new hooks which can be registered like this: app.service('myservice').hooks({
myCustomMethod: [
async (context, next) => {
console.log(`Doing things before ${context.method}`);
await next();
console.log(`Doing things after ${context.method}`);
}
}
}); Alternatively you can bring them closer to the service class using this format: import { hooks } from '@feathersjs/hooks';
export class MyService {
async find (params) {
return [];
}
async myCustomMethod (data, params) {
return data;
}
}
// Hooks for all service methods
hooks(MyService.prototype, [
authenticate('jwt')
]);
hooks(MyService, {
find: [
// find hooks here
],
myCustomMethod: [
async (context, next) => {
console.log(`Doing things before ${context.method}`);
await next();
console.log(`Doing things after ${context.method}`);
}
]
}) Or with TypeScript decorators ( import { HookContext } from '@feathersjs/feathers';
import { hooks, NextFunction } from '@feathersjs/hooks';
@hooks([
authenticate('jwt'),
async (context: HookContext, next: NextFunction) => {
console.log(`Class level hook before ${context.method}`);
await next();
console.log(`Class level hook after ${context.method}`);
}
])
export class MyService {
@hooks([
// find hooks here
])
async find (params) {
}
@hooks([
async (context: HookContext, next: NextFunction) => {
console.log(`Doing things before ${context.method}`);
await next();
console.log(`Doing things after ${context.method}`);
}
])
async myCustomMethod (data, params) {
return data;
}
} |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
forgot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Custom methods only work with the new hooks which can be registered like this:
Alternatively you can bring them closer to the service class using this format: