首页 > 解决方案 > 如何使用上下文而不是 args 过滤 type-graphql 订阅?

问题描述

我正在尝试向不同的用户发送通知,并希望每个用户只看到他的。我已经成功地用@Args 做你了。

以下是订阅:

@Subscription(() => Notification, {
    topics: "NOTIFICATIONS",
    filter: ({ payload, args }: ResolverFilterData<Notification, NewNotificationArgs>) => {
        return payload.userId === args.userId;
    },
})
newNotification(
    @Root() notification: Notification,
    @Args() { userId }: NewRequestArgs
): Notification {
   return notification;
}

和突变:

@Mutation(() => Boolean)
async createNotification(
    @PubSub("NOTIFICATIONS") notifyAboutNewNotification: Publisher<Notification>
): Promise<Boolean> {
    const notification = await Notification.create({
        userId: <some id>,
        message: <some message>
    }).save();

    await notifyAboutNewRequest(notification);

    return true;
}

现在我希望你使用一个 userId,我已经将它作为 cookie 存储在 context.req.session.userId 中。

标签: typegraphql

解决方案


ResolverFilterData包含有效载荷、参数、上下文和信息。所以你可以通过 filter: ({ context }) => { ... }.


推荐阅读