如何在Loopback 4中通过openapi-to-graphql启用GraphQL Subscription
问题解决步骤
你当前通过OAS回调自动生成的GraphQL Schema仅包含订阅的类型结构,未绑定对应的事件监听、数据推送逻辑,因此无法直接生效,需要补充自定义Resolver和事件发布逻辑,具体操作如下:
1. 编写自定义订阅Resolver
你需要为生成的Subscription字段定义subscribe和resolve逻辑,关联你已经初始化的PubSub实例:
const resolvers = { Subscription: { postRequestQueryCallbackUrlOnNotificationUpdate: { // 定义订阅监听的事件标识 subscribe: (parent, args, ctx) => ctx.pubsub.asyncIterator('NOTIFICATION_UPDATED'), // 定义返回给订阅端的数据格式 resolve: (payload) => payload.postRequestQueryCallbackUrlOnNotificationUpdate } } }
注意Resolver中的字段名必须和自动生成的Schema中的Subscription字段名完全一致
2. 注入Resolver到GraphQL Schema
修改你index.ts中创建GraphQL Schema的代码,把自定义Resolver传入配置:
const {schema} = await createGraphQLSchema(oas, { operationIdFieldNames: true, baseUrl: url, createSubscriptionsFromCallbacks: true, // 新增自定义Resolver配置 customResolvers: resolvers })
3. 绑定PubSub到应用上下文,补充事件发布逻辑
首先在index.ts中将PubSub实例注册到LB4应用的上下文,方便控制器调用:
const pubsub = new PubSub() // 新增绑定代码 app.bind('services.PubSub').to(pubsub)
之后修改你的控制器代码,注入PubSub并在通知更新操作完成后发布事件:
// 控制器构造函数中注入PubSub constructor( @repository(NotificationRepository) public notificationRepository : NotificationRepository, @inject('services.PubSub') private pubsub: PubSub ) {} @patch('/notification-update', { // 原有配置保持不变 }) async updateAll( // 原有参数保持不变 ): Promise<Count> { const count = await this.notificationRepository.update(notification, where); // 新增发布事件逻辑 this.pubsub.publish('NOTIFICATION_UPDATED', { // 字段名和Resolver中定义的保持一致 postRequestQueryCallbackUrlOnNotificationUpdate: JSON.stringify(notification) }) return count; }
4. 开启GraphiQL的WebSocket订阅支持
你当前的graphqlHTTP配置中GraphiQL默认没有开启WebSocket支持,需要补充订阅端点配置才能在GraphiQL中测试:
const handler = graphqlHTTP( (request:any, response:any, graphQLParams: any) => ({ schema, pretty: true, graphiql: { // 替换为你实际的服务地址 subscriptionEndpoint: `ws://localhost:${PORT}/subscriptions` } }))
以上步骤配置完成后即可正常测试订阅功能:先在GraphiQL中启动订阅,再调用PATCH更新通知接口,订阅端就能收到推送数据。
内容的提问来源于stack exchange,提问作者Rasyue
相关产品推荐
相关产品推荐

