How to exclude null fields in apollo graphql?

Member

by jasen , in category: Javascript , 3 months ago

How to exclude null fields in apollo graphql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 3 months ago

@jasen 

In Apollo GraphQL, you can set up resolvers to exclude null fields in your data responses. You can achieve this by adding logic in your resolver functions to check if a certain field in the data is null, and then exclude it from the response if needed.


Here is an example of how you can exclude null fields in a resolver function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const resolvers = {
  Query: {
    getUserData: async (_, args) => {
      const data = await fetchDataFromDatabase(args.userId);
      
      // Check if the user data has any null fields and exclude them from the response
      const filteredData = Object.keys(data).reduce((acc, key) => {
        if (data[key] !== null) {
          acc[key] = data[key];
        }
        return acc;
      }, {});
      
      return filteredData;
    },
  },
};


In the above code example, we have a getUserData resolver function that fetches user data from a database and then filters out any null fields before returning the data. This way, any null fields in the data will be excluded from the response.


You can apply similar logic in other resolver functions as needed to exclude null fields in your Apollo GraphQL responses.