用户数据未从查询调用返回任何内容

User data not returning anything from query call

我不确定我可能做错了哪一部分。我希望得到一些建议。

我在 GraphiQL 中使用的查询是:

query getUser($id:Int!) {
   user(id:$id) {
     id
    email
   }
}

对于后端,我使用的是 NodeJS。我还将用户类型声明为:

const UserType = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: { type: GraphQLID },
        email: { type: GraphQLString }
    })
});

我的根查询是:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        user: {
            type: UserType,
            args: { id: { type: GraphQLInt } },
            resolve(parentValue, args) {
                const query = `SELECT * FROM users WHERE id=`;
                const values = [ args.id ];
                dbQuery.query(query, values).then(({ rows }) => {
                    console.log(rows[0]);
                    return rows[0];
                });
            }
        }
    }
});

const schema = new GraphQLSchema({ query: RootQuery });
app.use(
    '/api/v1/graphql',
    graphqlHTTP({
        schema: schema,
        graphiql: true
    })
);

我在return中得到的是:

{
  "data": {
    "user": null
  }
}

我希望知道我可能做错了什么导致 returned 而不是我从数据库查询的数据。

感谢大家的帮助。

使用with await会更清楚

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        user: {
            type: UserType,
            args: { id: { type: GraphQLInt } },
            resolve: async(parentValue, args) {
                const query = `SELECT * FROM users WHERE id=`;
                const values = [ args.id ];
                const rows = await dbQuery.query(query, values);
                return rows[0];
            }
        }
    }
});

使用 promise 和 returning promise 中的任何内容时,只会 return 执行 promise 的结果。它不会 return 作为一个整体传递给父函数。

你也可以return像下面这样的整个promise函数

return dbQuery.query(query, values)