RedwoodJS启用GraphQL订阅失败,缺失哪些配置步骤?
问题:RedwoodJS GraphQL订阅提示“subscription操作类型不被允许”
从零开始创建TypeScript版本的RedwoodJS项目,执行命令:
yarn create redwood-app my-project
随后配置实验性服务器与实时功能:
yarn rw exp setup-server-file yarn rw exp setup-realtime
接着生成新的订阅:
yarn rw exp generate-realtime mySub
启动项目后:
yarn rw dev
在http://localhost:8911/graphql的GraphiQL端点执行订阅查询:
subscription ListenToMysubChannel { listenToMysubChannel(id: "1") { body from } }
收到错误:
{ "errors": [ { "message": "GraphQL operation type \"subscription\" is not allowed.", "locations": [ { "line": 1, "column": 1 } ] } ] }
解决步骤
需要手动修改服务器配置文件激活GraphQL订阅支持,具体操作如下:
修改
api/src/server.ts启用Apollo Server订阅功能
打开自动生成的api/src/server.ts,确保Apollo Server实例配置订阅支持,并挂载实时处理端点。示例配置:import { createServer } from '@redwoodjs/api' import { makeSchema } from '@redwoodjs/graphql-server' import { context } from './context' import { getDirectives, isAuthenticated } from './directives' import sdls from 'src/graphql/**/*.sdl.{js,ts}' import services from 'src/services/**/*.{js,ts}' import { createRealtimeHandler } from '@redwoodjs/realtime' const schema = makeSchema({ sdls, services, directives: getDirectives({ isAuthenticated }), }) const server = createServer({ schema, context, // 启用订阅路径配置 subscriptions: { path: '/graphql', }, }) // 挂载实时处理端点 const realtimeHandler = createRealtimeHandler({ schema, context }) server.use('/realtime', realtimeHandler) export default server配置GraphiQL支持WebSocket连接
在api/src/server.ts的Apollo Server配置中,为GraphiQL指定订阅的WebSocket端点:const server = createServer({ schema, context, subscriptions: { path: '/graphql', }, graphiql: { subscriptionsEndpoint: 'ws://localhost:8911/graphql', }, })验证订阅Schema与服务实现
检查api/src/graphql/mySub.sdl.ts是否包含正确的Subscription类型定义,以及api/src/services/mySub/mySub.ts中的订阅resolver是否正常实现。示例Schema:// api/src/graphql/mySub.sdl.ts export const schema = gql` type MySub { id: String! body: String! from: String! } type Subscription { listenToMysubChannel(id: String!): MySub! } `
完成以上修改后,重启yarn rw dev,再次执行订阅查询即可正常运行。
内容的提问来源于stack exchange,提问作者raylight
相关产品推荐
相关产品推荐

