Easy way to parse info.fieldNodes in order to make DB queries more Specific/Effiecient

Viewed 62

I'm creating queries by hand, defining them in my schema. So for example:

I'm using buildSchema. I'm not using graphql-js.

Query

companies: [Company]

types

type Company {
  id: Int!,
  name: String!,
  profile: CompanyProfile,
  featured: CompanyFeatured
},

resolver

companies: async () => CompanyController.findAll(),

The problem is I don't have an easy way to traverse incoming selected/requested fields from the AST:

info.fieldNodes[0].selectionSet.selections[0].name.value

I need an easy way to traverse the selected/requested set of fields and parse them into a cleaner nested JS object, so that I can then take and have my data layer parse through the specific set of fields in order to create more efficient queries to my database. I'm not sure the best way to go about collecting those requested fields so I can send them down to my DL.

Right now I'm returning ALL fields from the DB no matter what for a given type of data being requested which is not good.

I've seen this, but it's not really great. Are there easier ways or better ways to do this?

I use node-postgres and code the Data Layer myself. If I can just get these field selections somehow more easily to represent the same kinda of structure the fields show in the query into a JS object with the same structure incoming, I'll be on my way.

0 Answers
Related