Search code examples
typescripttypegraphql

applyResolversEnhanceMap not adding custom decorators to resolvers?


I'm using the typegraphql-prisma package and am trying to apply custom decorators to my generated resolvers to no avail. I'm trying to wrap my head around the bottleneck, but can't seem to identify it.

// src/lib/enhance.ts
export const mapped: ResolversEnhanceMap = {
  Like: {
    deleteLike: [RateLimitMiddleware()],
    createLike: [RateLimitMiddleware()],
  },
};
// src/lib/middleware.ts
const duration = 60 * 60;
const limit = 1;

export function RateLimitMiddleware() {
  console.log("Middleware is running...");
  // nothing below this line runs
  return createMethodDecorator<Context>(async ({ context, info }, next) => {
    const key = `rate-limit:${info.fieldName}:${context.user.user.id}`;
    console.log(key);
    const total = await redis.incr(key);
    if (total > limit) {
      throw new Error("You are being rate limited.");
    } else if (total === 1) {
      await redis.expire(key, duration);
    }
    return next();
  });
}
// src/index.ts
const app = express();
const http = createServer(app);
const schema = await buildSchema({
  resolvers: [...resolvers, AuthResolver, ImageResolver, CardResolver],
  validate: false,
});

applyResolversEnhanceMap(mapped);
// ... more code here

It doesn't seem like my RateLimit decorator is being applied at all? Each request goes through triggering any of the console.log. What am I missing?


Solution

  • For anyone having the same problem: the answer was to call applyResolversEnhanceMap before buildSchema.