【问题标题】:How to pass the values of a connection to a subscription?如何将连接的值传递给订阅?
【发布时间】:2023-04-08 13:38:02
【问题描述】:

我正在尝试返回包含以下内容的订阅:

const postsSubscription = gql`
  subscription postAdded {
    postAdded {
      id
      title
      description
      author{
        name
      }
    }
  }
`

发生的情况是作者是用户类型,我只是传递了一个作者 ID。这意味着我在创建帖子时没有作者姓名:

    createPost: async (root, req, { posts }) => {
      const Item = {
        id: uuid.v4(),
        authorId: '565dbdc0-36f2-4bba-be67-c126d0c71fff',
        ...req
      }
      await posts.create({ Item })

      pubsub.publish('postAdded', { postAdded: Item })

      return Item
    },

这是作者解析器:

Post: {
    author: async({ authorId }, req, { users }) => {
      const Key = { id: authorId }
      const { Item } = await users.get({ Key })

      return Item
    }
  }

这是架构:

type Post {
  id: ID
  title: String
  description: String
  author: User @relation(name: "PostAuthor")
}

type User {
  id: ID
  name: String
  email: String
  password: String
  posts: [Post] @relation(name: "UserPosts")
}

type PostPayload {
  post: Post
}

type CreateUserPayload {
  user: User
}

type Query {
  allPosts: [Post]
  allUsers: [User]
  post(id: ID!): Post
  user(id: ID!): User
}

type Mutation {
  createPost(input: CreatePostInput!): PostPayload
  updatePost(input : UpdatePostInput!): PostPayload
  createUser(input : CreateUserInput!): CreateUserPayload
}

type Subscription {
  postAdded: Post
}

input CreatePostInput {
  title: String!
  description: String!
}


input UpdatePostInput {
  id: ID!
  title: String!,
  description: String!
}

input CreateUserInput {
  name: String!
  email: String!
  password: String!
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

那么,我的问题是,如何将所有必填字段(包括连接)传递给订阅?

【问题讨论】:

  • 这个字段解析器被调用了吗?您也可以创建复制品或共享架构吗?
  • 你去@Urigo 它正在工作,因为当我查询allPostspost 时,我得到了作者。但我无法在订阅中获取此信息。所以它打破了,说它需要author

标签: graphql apollo react-apollo apollo-client


【解决方案1】:

我让它工作了,但不是我想要的。 1)我不得不删除这部分代码:

Post: {
  author: async({ authorId }, req, { users }) => {
    const Key = { id: authorId }
    const { Item } = await users.get({ Key })

    return Item
  }
}

并将此函数添加到 createPost 函数本身:

createPost: async (root, { input }, { posts, users }) => {
  const Key = { id: '3b1884b8-9ee7-4d9d-ab2f-ff32bcd69b9a' }
  const user = await users.get({ Key })

  const Item = {
    id: uuid.v4(),
    author: user.Item,
    ...input
  }
  await posts.create({ Item })
  await pubsub.publish(POST_ADDED_TOPIC, { [POST_ADDED_TOPIC]: Item })

  return { post: Item }
}

所以这有点固定。但是,如果您知道如何解决此问题,请使用第一种方法(帖子:author thingy),我将不胜感激。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2014-08-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多