#Custom decorator for field resolvers, get parent resolver
6 messages · Page 1 of 1 (latest)
What I came up until now:
export const Counter =
() =>
(target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => any>) => {
const className = target.constructor.name;
const name = `app_${className}_${propertyKey.toString()}_calls_total`;
const originalFunction = descriptor.value ?? (() => {});
const wrappedFunction = function PropertyDescriptor(...args: any[]) {
console.log('name', name);
console.log('target', target.constructor);
console.log('propertyKey', propertyKey);
console.log('descriptor', descriptor.value);
return originalFunction.apply(this, args);
};
// eslint-disable-next-line no-param-reassign, func-names
descriptor.value = wrappedFunction;
Reflect.getMetadataKeys(originalFunction).forEach((metadataKey) => {
Reflect.defineMetadata(metadataKey, Reflect.getMetadata(metadataKey, originalFunction), wrappedFunction);
});
};
but there doesn't seem to be a way to fetch the parent resolver if I use this decorator above a @ResolveField
I don't think that's possible out of the box, since the field resolvers are ran after the parent resolver is finished (not while it's running).
You could store a reference in the context, but there's no guarantee that it will be correct. Imagine following graphql query:
query UserTwoDifferentWays {
user(id: 123) { username }
userByEmail(email: "who@isparent.com") { username }
}
If I'm not mistaken, the order of execution is not guaranted, so it could be called in this order:
- user resolver
- userByEmail resolver
- username resolver for user query
- username resolver for userByEmail query