How to return custom object from resolver in graphql?

by darrion.kuhn , in category: Javascript , 7 months ago

How to return custom object from resolver in graphql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 7 months ago

@darrion.kuhn 

To return a custom object from a resolver in GraphQL, you can create an instance of an object and return it as the resolver's result. Here is an example of how you can do this in a typical resolver function:

  1. Define your custom object class:
1
2
3
4
5
6
class CustomObject {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}


  1. Create a resolver function that returns an instance of the custom object:
1
2
3
4
5
6
7
8
const resolvers = {
  Query: {
    getCustomObject: () => {
      const customObject = new CustomObject(1, 'CustomObject1');
      return customObject;
    },
  },
};


In this example, the getCustomObject resolver function returns a new instance of the CustomObject class with an id of 1 and a name of 'CustomObject1'.

  1. Modify your GraphQL schema to include the custom object type and resolver:
1
2
3
4
5
6
7
8
type CustomObject {
  id: ID!
  name: String!
}

type Query {
  getCustomObject: CustomObject!
}


With this setup, when you query for getCustomObject in your GraphQL API, the resolver will return an instance of the custom object with the specified fields.