如何从回调返回值?

时间:2020-01-03 18:37:05

标签: node.js typescript graphql grpc apollo

我正在尝试将GraphQL(Apollo / Node.js)和gRPC(Go)粘合在一起。到目前为止,我可以在它们之间进行通信。

但是,我无法从gRPC客户端回调中返回创建的用户值。

这是用户架构;

// schema.ts

import {gql} from 'apollo-server-express'

const schema = gql`
  type Mutation {
    addUser(input: AddUser): User
  }

  type User {
    id: ID!
    email: String
  }

  input AddUser {
    email: String!
    password: String!
  }
`

export default schema

这是解析器;

// resolver.ts

import {add} from '../client'

const resolver = {
  Query: {
    users: () => console.log('in progress'),
  },
  Mutation: {
    // addUser: (_: any, {input}: any) => add(input),

    // This successfully logs the `res`
    // addUser: (_: any, {input}: any) => add(input, (res: any) => console.log('Logged from resolver >', res)),

    // This returns null in mutation
    addUser: (_: any, {input}: any) => add(input, (res: any) => {
      return res
    }),
  }
}

export default resolver

这是gRPC客户端,它返回undefined。

// client.ts

export async function add(input: any) {

  // Confirmed created in database
  client.addUser({
    email: input.email,
    password: input.password
  }, (_err: any, res: any) => {

    // Successfully logs `res`
    console.log('Logged res here > ', res)

    return res
  })
}

请帮助我。


编辑:

我还尝试了回调函数:

export async function add(input: Input, callback: any) {
  try {
    await client.addUser({
      email: input.email,
      password: input.password
    }, (_err: any, res: any) => {
      console.log('Logged res here > ', res)
      return callback(res)
    })
  } catch (error) {
    console.log(error);
  }
}

在突变中仍然返回null:

    addUser: (_: any, {input}: any) => add(input, (res: any) => {
      return res
    }),

1 个答案:

答案 0 :(得分:2)

GraphQL解析器应该返回适​​当类型的值,或者返回将解析为该值的Promise。回调和Promises都是异步处理代码的两种方式,但是它们不兼容。

尚不清楚您使用的是哪个客户端库,但是现在大多数使用回调的库也公开了Promise API -如果您使用的则应使用该API。如果这不是一个选择,则应wrap the callback with a Promise。像这样:

const resolver = {
  Mutation: {
    addUser: (_: any, {input}: any) => new Promise((resolve, reject) => {
      add(input, (res) => {
        resolve(res)
      })
    }),
  },
}

请注意,如果回调函数传递了错误,则应确保使用错误调用reject而不是调用resolve

相关问题