0

I'm not sure which part I might be doing wrong. I was hoping to get some advice.

The query I am using in GraphiQL is:

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

For the backend I am using NodeJS. I am also declaring the user type as:

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

My root query is:

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        user: {
            type: UserType,
            args: { id: { type: GraphQLInt } },
            resolve(parentValue, args) {
                const query = `SELECT * FROM users WHERE id=$1`;
                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
    })
);

What I get in return is:

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

I was hoping to know what I might be doing wrong that is resulting in null being returned instead of the data that I am querying from the database.

Thank you for all the help.

1 Answer 1

1

It will be much more clear if you use 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=$1`;
                const values = [ args.id ];
                const rows = await dbQuery.query(query, values);
                return rows[0];
            }
        }
    }
});

When using a promise and returning anything inside the promise will only return the result to the promise that is executed. It will not be returning as a whole to the parent function.

You can also return the whole promise function like below

return dbQuery.query(query, values)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for responding. I have tried doing both and the response I get back is null. The first approach instead returned user: { id: null, email: null} even though there is data being returned from the resolver.
It started to work. I'm not sure what I changed or what I may have done wrong but your answer was very helpful. Thank you so much :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.