如何使用上下文而不是参数来过滤 type-graphql 订阅?

How to filter type-graphql subscription using context, instead of args?

我正在尝试向不同的用户发送通知,并希望每个用户只能看到他的。我已经成功地用@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 中。

我记录了我的上下文,看起来我正在获取值,但未定义。您需要使用 onConnect 事件来升级上下文。

对我有帮助的链接: Discussion Youtube

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

访问它