简体   繁体   中英

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 Author type I would:

import graphql from 'graphql'
export default new graphql.GraphQLObjectType({
  description: `An author`,
    name: {
      description: `The author's legal name.`,
      type: GraphQLString
    }
  }),
  name: `Author`
})

So the type definition here is generated by GraphQLObjecType . What function generates fragments?

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.

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM