0
votes

I need to provide custom custom Object as ouput for GraphQL resolver.

This is for Node-Express backend server with GraphQL setup. I tried sequelized, but I'm testing a new approach, where i need to pass an object as output to graphQL.

const RootQueryType = new GraphQLObjectType({
  name: "Query",
  fields: {
  Sample: {
      type: SampleType,
      args: {
        sampleID: { type: GraphQLID }
      },
      resolve: async (parent, args) => {
        try {
          const result = await sql.connect(config).then(pool =>
            pool
              .request()
              .input("sampleID", sql.Int, args.sampleID)
              .query(
                "SELECT * FROM samples WHERE sampleID = @sampleID"
              )
          );
          const ASB = await result.recordsets[0];
          console.log(ASB);
          sql.close();
          return ASB;
        } catch (err) {
          console.log(err);
          sql.close();
          return;
        }
      }
    }
  }
});

the result of the query output is

[
  {
     sampleID: 1,
     sampleText: 'sample1'
  },
  {
     sampleID: 2,
     sampleText: 'sample2'
  }
]

When i return plain object i.e. ASB[0]

{
     sampleID: 1,
     sampleText: 'sample1'
}

I am getting output in GraphQL but when the entire ASB object is returned, I'm not able to get ouput.

1

1 Answers

0
votes

The problem is you're declaring the type as single item SampleType but returning the array of SampleType

you can fix it be changing SampleType to new GraphQLList(SampleType)

const RootQueryType = new GraphQLObjectType({
  name: "Query",
  fields: {
  Sample: {
      type: new GraphQLList(SampleType), // THIS LINE !!!
      args: {
        sampleID: { type: GraphQLID }
      },
      resolve: async (parent, args) => {
        try {
          const result = await sql.connect(config).then(pool =>
            pool
              .request()
              .input("sampleID", sql.Int, args.sampleID)
              .query(
                "SELECT * FROM samples WHERE sampleID = @sampleID"
              )
          );
          const ASB = await result.recordsets[0];
          console.log(ASB);
          sql.close();
          return ASB;
        } catch (err) {
          console.log(err);
          sql.close();
          return;
        }
      }
    }
  }
});