Skip to content Skip to sidebar Skip to footer

How Do You Define A Fragment Using Graphql-js?

How do I define fragments in my schema using graphql-js? import graphql from 'graphql' /* how do I do this? fragment authorInfo on Author { name } */ For example, to define the

Solution 1:

Fragments are used to group the fields and reuse them on the client-side. They are not something you should worry about at the server and while you are creating the schema.

The client-side code should provide the fragments when querying the data from the server. GraphQL itself takes care of adding the fragmented fields on the query. On the server, you need to specify all the fields on all the objects.

Of course you can write your own helpers to reduce the manual work.

Same goes with variables too.

Solution 2:

you do not define fragment in the schema. you define on the graphql interface when you do query. this is about do not repeat yourself.

We can make as many as different queries inside a query{ }

query {
   company(id:"1"){
    name
    description
  }
  company(id:"4"){
    name
    description
  }
}

if you do so you will get an ERROR: fields “company” conflicts because they have different arguments. To get rid of this, we can name the result of the query when it comes back by writing out some arbitrary key in front. the reason why we get this error is response object will have 2 nested objects and they both will have "company" key value but inside javascript we cannot have duplicate keys on an object.

{
  apple: company(id:"1"){
    name
    description
  }
  google: company(id:"4"){
    name
    description
  }
}

now we tackled this. imagine we wanna do 100 queries in a single query object with too many fields. it would be a big headache. so we define fragment

fragment companyDetails on Company{  
  name
  description
  }

note that we have to specify on Company. It helps graphql for type checking. graphql checks if those fields are valid under company. finally this is how we use it

{
  apple: company(id:"1"){
    ...companyDetails
  }
  google: company(id:"4"){
    ...companyDetails
  }
}

Post a Comment for "How Do You Define A Fragment Using Graphql-js?"