簡體   English   中英

訂閱 GraphQL 服務器時出錯

[英]Error on subscription GraphQL Server

我對 GraphQl 還很陌生,我在這里學習了 GraphQL NodeJS 后端教程: GraphQL 實時訂閱 一切正常,我完成了教程。 接下來,我在此處遵循 VueJS 和 Apollo 前端教程: Vue & Apollo Subscriptions 我在第一個教程中選擇使用我自己創建的 GraphQL 服務器,而不是使用前端教程中使用的 GraphCool。 這是我被卡住的部分。 如果我打電話

subscription {
    Link(filter: {
      mutation_in: [CREATED]
    }) {
      node {
        id
        url
        description
      }
    }
}

在 GraphiQL 客戶端中,當我在不同的瀏覽器選項卡中使用數據data: Link: node: {id: "59ef0bbeef32bb05692ee4b4", url: "http://new-test-url2.com", description: "Test description2"}創建新鏈接時,我確實得到了idurldescription data: Link: node: {id: "59ef0bbeef32bb05692ee4b4", url: "http://new-test-url2.com", description: "Test description2"} (這個訂閱調用也是在后台教程中進行的)。 但是當我打電話

subscription {
    Link(filter: {
      mutation_in: [CREATED]
    }) {
      node {
        id
        url
        description
        postedBy {
          id
          name
        }
        votes {
          id
          user {
             id
          }
        }
      }
    }
  }

我收到錯誤:

{message: "Cannot destructure property `Users` of 'undefined' or 'null'.",…}
{message: "Cannot destructure property `Votes` of 'undefined' or 'null'.",…}

與數據data:{Link: {node: null}}

我只是找不到這個問題的答案。 希望有人能幫我這個。 這是我的代碼:

架構/index.js

type Link {
    id: ID!
    url: String!
    description: String!
    postedBy: User
    votes: [Vote!]!
}

type User {
    id: ID!
    name: String!
    email: String!
    password: String!
    votes: [Vote!]!
}

type Vote {
    id: ID!
    user: User!
    link: Link!
}

type SigninPayload {
    token: String
    user: User
}

type Query {
    allLinks(filter: LinkFilter, skip: Int, first: Int): [Link!]!
}

type Mutation {
    createLink(url: String!, description: String!): Link

    createVote(linkId: ID!): Vote

    createUser(name: String!, email: String!, password: String!): User

    signinUser(email: String!, password: String!): SigninPayload!
}

type Subscription {
    Link(filter: LinkSubscriptionFilter): LinkSubscriptionPayload
    Vote(filter: VoteSubscriptionFilter): VoteSubscriptionPayload
}

input LinkSubscriptionFilter {
    mutation_in: [_ModelMutationType!]
}

input VoteSubscriptionFilter {
    mutation_in: [_ModelMutationType!]
}

type LinkSubscriptionPayload {
    mutation: _ModelMutationType!
    node: Link
}

type VoteSubscriptionPayload {
    mutation: _ModelMutationType!
    node: Vote
}

input LinkFilter {
    OR: [LinkFilter!]
    description_contains: String
    url_contains: String
}

enum _ModelMutationType {
    CREATED
    UPDATED
    DELETED
}

架構/resolvers.js:

Query: {
    allLinks: async (root, {filter, first, skip}, {mongo: {Links, Users}}) => {
        let query = filter ? {$or: buildFilters(filter)} : {};
        const cursor = Links.find(query);
        if (first) {
            cursor.limit(first);
        }

        if (skip) {
            cursor.skip(skip);
        }

        return cursor.toArray();
    },
},

Mutation: {
    createLink: async (root, data, {mongo: {Links}, user}) => {

        assertValidLink(data);
        const newLink = Object.assign({postedById: user && user._id}, data);
        const response = await Links.insert(newLink);

        newLink.id = response.insertedIds[0];

        pubsub.publish('Link', {Link: {mutation: 'CREATED', node: newLink}});

        return newLink;
    },

    createUser: async (root, data, {mongo: {Users}}) => {
        const newUser = {
            name: data.name,
            email: data.email,
            password: data.password,
        };

        const response = await Users.insert(newUser);

        return Object.assign({id: response.insertedIds[0]}, newUser);
    },

    createVote: async (root, data, {mongo: {Votes}, user}) => {
        const newVote = {
            userId: user && user._id,
            linkId: new ObjectID(data.linkId),
        };

        const response = await Votes.insert(newVote);

        return Object.assign({id: response.insertedIds[0]}, newVote);
    },

    signinUser: async (root, data, {mongo: {Users}}) => {
        const user = await Users.findOne({email: data.email});
        if (data.password === user.password) {
            return { token: `token-${user.email}`, user };
        }
    },
},

Subscription: {
    Link: {
        subscribe: () => pubsub.asyncIterator('Link'),
    },
},

Link: {
    id: root => root._id || root.id,

    // postedBy: async ({postedById}, data, {dataloaders: {userLoader}}) => {
    //     return await userLoader.load(postedById);
    // },

    postedBy: async ({postedById}, data, {mongo: {Users}}) => {
        return await Users.findOne({_id: postedById});
    },

    votes: async ({_id}, data, {mongo: {Votes}}) => {
        return await Votes.find({linkId: _id}).toArray();
    },
},

這么久了,希望你能解決這個問題,我今天才自己解決了這個問題。 這里的問題是訂閱服務器從未在上下文中傳遞,即數據加載器/用戶信息。

在本課( https://www.howtographql.com/graphql-js/4-connectors/ )中,您設置了快速服務器的上下文,但從未將其添加到訂閱服務器中:

  const buildOptions = async (req,res) => {                                                     
const user = await authenticate(req, mongo.Users)                                           
return {                                                                                    
  context: {                                                                                
    dataloaders: buildDataloaders(mongo),                                                   
    mongo,                                                                                  
    user                                                                                    
  },                                                                                        
  formatError,                                                                              
  schema,                                                                                   
}                                                                                           

為了將其添加到訂閱服務器,我自己使用了以下選項:

const subscriptionBuildOptions = async (connectionParams,webSocket) => 
{                      
  return {                                                                                   
    dataloaders: buildDataloaders(mongo),                                                    
    mongo,                                                                                   
  }
}  

然后我通過簡單地添加 onConnect 參數將它添加到 SubscriptionServer:

const server = createServer(app);                                                             
server.listen(PORT, () => {                                                                   
  SubscriptionServer.create(                                                                  
    {execute, subscribe, schema, onConnect: subscriptionBuildOptions},                        
    {server, path: '/subscriptions'},                                                         
  );                                                                                          
  console.log(`Hackernews GraphQL server running on port ${PORT}.`)                           
}); 

這應該主要使一切正常。 我個人正在做 reactjs 教程,所以不確定會有什么個別問題,但是 reactjs 教程 api 調用在整個過程中有點不同步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM