WebSocket订阅服务器不工作,无法访问订阅服务器graphql-ws ws

y0u0uwnf  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(206)

我遵循[相同的文档代码][1]使用WebSocket graphql创建订阅服务器,把它不与graphql-ws和ws一起工作当我删除serverql定义时,代码工作,它也适用于旧的订阅库“subscription-transfer-ws”my index.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]",
    "gender":"male",
    "mobile":"734-324-1043",
    "cumulativeGPA":92.1,
    "isGraduated":true,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected]",
          "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]",
    "gender":"male",
    "mobile":"165-705-3521",
    "cumulativeGPA":90.6,
    "isGraduated":false,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected]",
          "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]",
    "gender":"male",
    "mobile":"734-324-1043",
    "cumulativeGPA":92.1,
    "isGraduated":true,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected]",
          "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]",
    "gender":"male",
    "mobile":"165-705-3521",
    "cumulativeGPA":90.6,
    "isGraduated":false,
    "friends":[
       {
          "name":"Magdalena",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"734-324-1043",
          "cumulativeGPA":92.1
       },
       {
          "name":"Harman",
          "email":"[email protected]",
          "gender":"male",
          "mobile":"158-265-8979",
          "cumulativeGPA":87.9
       },
       {
          "name":"Oliver",
          "email":"[email protected]",
          "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/

mbskvtky

mbskvtky1#

我遇到了类似的问题,对我起作用的是以下几点:
1.进入Apollo Studio沙盒中的“Explorer Settings”(齿轮图标)。
1.点击“编辑”
1.将“订阅”端点设置为“ws://localhost:4000/graphql”
1.将“实现”更改为“graphql-ws”
1.保存并重试订阅操作

相关问题