websocket 订阅服务器不工作。无法到达订阅服务器 graphql-ws ws

2024-05-01

我遵循[相同的文档代码][1]使用websocket graphql创建订阅服务器,但它不适用于graphql-ws和ws 当我删除 serverCleanup 定义时,代码有效,并且它也适用于旧的订阅库“subscription-transport-ws”我的索引.js

const { ApolloServer } = require('apollo-server-express')
const { ApolloServerPluginDrainHttpServer } = require('apollo-server-core')
const express = require('express')
const http = require('http')
const { makeExecutableSchema } = require('@graphql-tools/schema')
const { upperDirectiveTransformer } = require('./directives/uppercase')
const { WebSocketServer } = require ('ws');
const { useServer } = require('graphql-ws/lib/use/ws');
const { typeDefs } = require('./typeDefs')
const { resolvers } = require('./resolvers')
const jwt = require('jsonwebtoken');
const JWT_SECRET = 'f1BtnWgD3VKY';
const users = [
 {
    "id":1,
    "name":"Magdalena",
    "email":"[email protected] /cdn-cgi/l/email-protection",
    "gender":"male",
    "mobile":"734-324-1043",
    "cumulativeGPA":92.1,
    "isGraduated":true,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"female",
          "mobile":"500-958-5193",
          "cumulativeGPA":67.9
       }
    ],
    "age":28,
    "image" : {"name":"ghklk.png", "height": 50 , "width":30},
    "idea": "auction",
    "grantedAmount": 12000
 },
 {
    "id":2,
    "name":"Lyndell",
    "email":"[email protected] /cdn-cgi/l/email-protection",
    "gender":"male",
    "mobile":"165-705-3521",
    "cumulativeGPA":90.6,
    "isGraduated":false,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"female",
          "mobile":"500-958-5193",
          "cumulativeGPA":67.9
       }
    ],
    "age":23,
    "image" : {"name":"ghklk.png", "height": 50, "width":30},
    "idea": "e-collage",
    "grantedAmount": 0
 },
 ]

async function startApolloServer(typeDefs, resolvers) {
    const app = express()
    const httpServer = http.createServer(app)

    let schema = makeExecutableSchema({
        typeDefs,
        resolvers
    })

    schema = upperDirectiveTransformer(schema, 'upper')

    const wsServer = new WebSocketServer({
        server: httpServer, 
        path: '/graphql'
    })
    const serverCleanup = useServer({ schema }, wsServer);

    const server = new ApolloServer({
        schema,
        plugins: [
            ApolloServerPluginDrainHttpServer({ httpServer }),
            {
                async serverWillStart() {
                  return {
                    async drainServer() {
                        serverCleanup.dispose();
                    }
                  }
                }
            }
        ],
        context: ({ req }) => {
            const auth = req ? req.headers.authorization : null 
            try{
                const decodedToken = jwt.verify(auth.slice(4), JWT_SECRET)
                const user = users.find(user => user.id == decodedToken.id)
                return { user }
            }catch(err){
                return null
            }
        }
    })

    await server.start()
    server.applyMiddleware({ app })
    await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve))
    console.log(`???? Server ready at http://localhost:4000${server.graphqlPath}`);
    return { server, app }
}

startApolloServer(typeDefs, resolvers)

我的解析器.js

const users = [
 {
    "id":1,
    "name":"Magdalena",
    "email":"[email protected] /cdn-cgi/l/email-protection",
    "gender":"male",
    "mobile":"734-324-1043",
    "cumulativeGPA":92.1,
    "isGraduated":true,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"female",
          "mobile":"500-958-5193",
          "cumulativeGPA":67.9
       }
    ],
    "age":28,
    "image" : {"name":"ghklk.png", "height": 50 , "width":30},
    "idea": "auction",
    "grantedAmount": 12000
 },
 {
    "id":2,
    "name":"Lyndell",
    "email":"lgilbee[email protected] /cdn-cgi/l/email-protection",
    "gender":"male",
    "mobile":"165-705-3521",
    "cumulativeGPA":90.6,
    "isGraduated":false,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected] /cdn-cgi/l/email-protection",
          "gender":"female",
          "mobile":"500-958-5193",
          "cumulativeGPA":67.9
       }
    ],
    "age":23,
    "image" : {"name":"ghklk.png", "height": 50, "width":30},
    "idea": "e-collage",
    "grantedAmount": 0
 }]
const { PubSub } = require('graphql-subscriptions')
const pubSub = new PubSub()
const resolvers = {
    Gender: {
      MALE: 'male',
      FEMALE: 'female',
    },
    Query: {
      getUserByID: (_, {id}) => users.find(user => user.id == id),
      users: () => users,
    },
    Mutation: {
      createUser: async (_, args) => {
        if (users.find(user => user.email === args.email)) {
          throw new Error('user already exist')
        }
        const user = { ...args, id: users.length + 1 };
        users = users.concat(user);
        pubSub.publish('USER_ADDED', { userAdded: user })
        return user
      }
    },
    Subscription: {
      userAdded: {
        subscribe: () => pubSub.asyncIterator(['USER_ADDED']),
      }
    }
};

module.exports = { resolvers };

typeDefs.js

const { gql } = require('apollo-server-express');

const typeDefs = gql`
    type User {
        id: ID!
        name: String!
        email: String!
        gender: Gender!
        mobile: String!
        cumulativeGPA:Float!
        isGraduated: Boolean
        friends: [Friend]!
        age: Int!
        image: Image
    }

    enum Gender {
        MALE
        FEMALE
    }

    type Friend{
        name: String!
        email: String!
        gender: Gender!
        mobile: String!
        cumulativeGPA:Float!
    }

    type Image{
        name: String!
        height: Int!
        width: Int!
    }

    type Query {
        users: [User]
        getUserByID(id: ID!): User
    }

    type Mutation {
        createUser(
            name: String!
            email: String!
            gender: Gender!
            mobile: String!
            cumulativeGPA:Float!
            isGraduated: Boolean
            friends: [FriendInput]!
            age: Int!
            image: ImageInput
        ): User
    }

    type Subscription {
        userAdded: User
    }

    input ImageInput{
        name: String!
        height: Int!
        width: Int!
    }

    input FriendInput{
        name: String!
        email: String!
        gender: Gender!
        mobile: String!
        cumulativeGPA:Float!
    }

`;

module.exports = { typeDefs };

没有客户端,只是我需要在 apollo-sandbox 上尝试从服务器端订阅 [1]:https://www.apollographql.com/docs/apollo-server/data/subscriptions/ https://www.apollographql.com/docs/apollo-server/data/subscriptions/


我遇到了类似的问题,对我有用的是以下内容:

  1. 进入 Apollo Studio 沙箱中的“资源管理器设置”(齿轮图标)。
  2. 点击“编辑”
  3. 将“订阅”端点设置为“ws://localhost:4000/graphql”
  4. 将您的“实现”更改为“graphql-ws”
  5. 保存并再次尝试您的订阅操作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

websocket 订阅服务器不工作。无法到达订阅服务器 graphql-ws ws 的相关文章

随机推荐

  • 将 NSString 中的“”字符替换为“\”(以创建 Unix 路径)

    使用以下内容不起作用 NSString stringByReplacingOccurrencesOfString NSString target withString NSString replacement 我所说的 不起作用 是指不做任
  • 如何在 C# 中对包含日期的字符串数组进行排序?

    我不确定以前是否有人问过这个问题 但我有几个需要排序的字符串数组 这个想法是合并不同的字符串数组并按每个元素的日期字段对它们进行排序 我正在从 sql server 表中读回信息 我怎样才能去做这样的事情呢 数据示例可能如下所示 类型 字段
  • 从 Java 访问文件名中带有空格的文件

    我想从java程序访问文件名中有空格的目录中的文件 但它不访问文件 场景是我在文件中有文件名 iread 从该文件中读取文件名 但无法在 java 中打开带有空格的文件 我们使用 File exist 函数来检查文件是否存在 但它返回 fa
  • Github 操作/缓存工作的限制在什么范围内?

    我不太明白Github到了什么程度动作 缓存有效 我的意思是 如果我发出拉取请求 然后在同一个拉取请求中添加 1 个提交 则缓存工作正常 但如果我在同一分支中创建新的拉取请求 缓存将重置并再次启动 但为什么呢 有没有办法将文件缓存扩展到所有
  • 我们应该首先调用 MobileAds.setRequestConfiguration 还是 MobileAds.initialize?

    这方面没有太多文档 我想知道我们应该先打电话吗 RequestConfiguration conf new RequestConfiguration Builder setMaxAdContentRating MAX AD CONTENT
  • 尝试从 Polar H10 获取心率变异性 [蓝牙低功耗示例 UWP]

    我正在与 Polar H10 合作 从中获取心率变异性 我在跑步蓝牙低功耗示例 https github com Microsoft Windows universal samples tree master Samples Bluetoo
  • Java、Jacob 和 Microsoft Outlook 事件:收到“找不到事件 iid”错误

    我正在编写一个 Java 程序 它使用雅各布图书馆 http danadler com jacob 桥接 COM 和 Java 该程序创建了一个新的MailItem http msdn microsoft com en us library
  • 如何在 R 中连接数字列?

    我在 R 的数据框中有三列 x y 和 z 坐标 我想将其连接成一个 xyz 值 如下所示 我尝试过使用 collapse 和 sep 粘贴 但遇到了麻烦 我认为这与文本与数字变量有关 I have x y z 1 2 3 2 3 2 3
  • EditText 在 ScrollView 中不可滚动[重复]

    这个问题在这里已经有答案了 我有一个ScrollView里面是一个EditText设置为垂直滚动 但它不滚动 相反 整个布局滚动 每当我尝试滚动EditText 下面是代码
  • 从 iOS Facebook 2.x -> 3.x 迁移时如何避免用户注销

    将 Facebook iOS 集成从 2 x SDK 升级到 3 x SDK 会自动注销之前登录的用户 因为我们过去必须手动处理的身份验证凭据现在由新的 SDK 在幕后处理 SDK 有没有办法强制 3 x SDK 使用我们之前手动存储的访问
  • 减少内存分配GCC命令

    今天 在我的计算机科学课上 我被告知我可以调整程序在编译期间可以分配的内存量 使用 GCC Linux 该数量默认设置为最佳模式 这意味着尽可能多 在调试应用程序期间 我可以从这个编译器功能中受益匪浅 因为我需要正确处理分配错误 这在我的
  • ember-cli 在 --environment=product 上失败(未捕获错误:找不到模块)

    我正在使用 ember cli 并且在选择生产环境时遇到问题 具体来说 当我跑步时一切正常ember serve environment development当我运行时我得到一个空白页ember serve environment pro
  • HTML 到 CALS 表?

    我正在检查是否有人拥有可将 HTML 表转换为 CALS 的 XSLT 我发现了很多关于采用其他方式 CALS 到 HTML 的材料 但没有找到来自 HTML 的材料 我认为以前可能有人这样做过 所以我不必重新发明轮子 我并不是在寻找完整的
  • 将 Pandas GroupBy 多索引输出从 Series 转换回 DataFrame

    我有一个数据框 City Name 0 Seattle Alice 1 Seattle Bob 2 Portland Mallory 3 Seattle Mallory 4 Seattle Bob 5 Portland Mallory 我执
  • Dagger2自定义@Qualifier用法

    假设我正在制造一辆汽车 并且我有几个具有不同实现的 Brake beans class Car Inject Car BrakeType value abs Brake frontBrake BrakeType value nonabs B
  • 文本组件中的 ASCII 不可打印字符

    我的情况是 我必须扫描文本字段中的二维码 我必须解析该文本字段附带的不可打印字符 顺便说一句 它总是相同的字符 而这些字符永远不会出现在相同的位置 我尝试获取此代码但没有成功 textfield getText 失败 textfield g
  • 基本编程/算法概念[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我即将 与其他程序员一起 在我的高中
  • 在不同时区之间格式化时间的正确方法是什么?

    我想将 19 19 00 之类的时间格式化为不同的时区 如果我使用SimpleDateFormat它始终考虑纪元的开始 1970 01 01 有些时区在纪元开始时和现在有不同的偏移量 例如 现在与欧洲 基辅的默认偏移量是 UTC 0200
  • Power Query 按组的列总和作为新列

    所以我对电源查询很陌生 我只是浪费了一个多小时来寻找可以在许多其他程序中轻松完成的事情 我只想创建一个新列来总结另一列 例如 检查百分比是否正确 如果不正确则将其归一化 我不想分组并减少表格 我一直在左右搜索 并尝试使用诸如 Group S
  • websocket 订阅服务器不工作。无法到达订阅服务器 graphql-ws ws

    我遵循 相同的文档代码 1 使用websocket graphql创建订阅服务器 但它不适用于graphql ws和ws 当我删除 serverCleanup 定义时 代码有效 并且它也适用于旧的订阅库 subscription trans