简体   繁体   中英

From where does Relay fetch the Schema of GraphQL?

I am having a running GraphQL based server and I am able to test it properly using GraphiQL. But I am unable to understand the implementation of Relay.

As GraphQL is on the server side, then how its schema is transferred to relay over network layer at the client end? Or how it is pointing to the same GraphQL?

It takes a little extra work. Basically you have to dump a serialized version of the schema to a file on the server side, and then move that file over to the client and include it during babel compilation. Facebook has a babel plugin that takes this file and builds it into the bundle in order for Relay to know about the schema.

EDIT: here is a snippet for how to dump the schema file to JSON

import { graphql }  from 'graphql'
import { introspectionQuery, printSchema } from 'graphql/utilities'

/*
  generates json of our schema for use by relay
 */
export default function (schema) {
  return new Promise((resolve, reject) => {
    graphql(schema, introspectionQuery).then(result => {
      if (result.errors) {
        console.error(`ERROR introspecting schema: ${result.errors}`)
        reject(new Error(result.errors))
      } else {
        resolve({ json: result, graphql: printSchema(schema) })
      }
    })
  })
}

After you obtain that, you have to npm install babel-relay-plugin and include that in your babel plugins (probably in the webpack config, if you're using that).

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