How to return a rejected promise to graphql?

Member

by mac , in category: Javascript , 5 months ago

How to return a rejected promise to graphql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 5 months ago

@mac 

To return a rejected promise in GraphQL, you can throw an error in your resolver function. When an error is thrown, GraphQL will automatically handle it and return an error response to the client.


Here is an example of how you can return a rejected promise in a resolver function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const { GraphQLObjectType, GraphQLString, GraphQLSchema } = require('graphql');

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

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    user: {
      type: UserType,
      resolve(parent, args) {
        // Simulating a rejected promise
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            reject(new Error('User not found'));
          }, 1000);
        });
      }
    }
  }
});

const schema = new GraphQLSchema({
  query: RootQuery
});

module.exports = schema;


In this example, the user resolver function returns a promise that is immediately rejected with an error message. When the client makes a request for the user field, GraphQL will catch the rejected promise and return an error response to the client with the message "User not found".