relay学习笔记(3)

在React app中使用Relay,我们有两件事情要做

(1)createContainer,

(2)fragement

containers:component可以从container中获取数据。
使用Realy.createContainer方法,传递两个参数,第一个参数是需要数据的Component.第二个是Component所需的数据fragements。
fragement通过执行Relay请求获取数据。
fragments: {
    author: () => Relay.QL`
    fragment on Author {
      _id
      name
      avatarUrl
      bio
      books(first: 100) {
        count
        edges {
          node {
            slug
            ${BookItem.getFragment('book')}
          }
        }
      }
    }`

  由于我们使用字符串来表示请求,很容易写错,因此我们可以使用babel-realy-plugin来:

(1)读取Relay.QL字符串

(2)转换为GraphQL请求

(3)对照schema验证请求。

如何获取服务端的schema呢,可以将服务端的schema导出为一个json文件。schema.json,我们可以指定babel-realy-plugin使用这个文件,当我们编译客户端代码的时候。

import fs from 'fs';
import path from 'path';
import { graphql } from 'graphql';
import { introspectionQuery, printSchema } from 'graphql/utilities';
import schema from '../schema';

// Save JSON of full schema introspection for the Babel Relay Plugin to use
const generateJSONSchema = async () => {
  var result = await (graphql(schema, introspectionQuery));
  if (result.errors) {
    console.error(
      'ERROR introspecting schema: ',
      JSON.stringify(result.errors, null, 2)
    );
  } else {
    fs.writeFileSync(
      path.join(__dirname, '../client/src/data/schema.json'),
      JSON.stringify(result, null, 2)
    );
  }

  // Save user readable type system shorthand of schema
  fs.writeFileSync(
    path.join(__dirname, '../client/src/data/schema.graphql'),
    printSchema(schema)
  );
};

generateJSONSchema().then(() => {
  console.log("Saved to client/src/data/schema.{json,graphql}");
})

  

(4)将请求转化为一个扩大的方法。

 

fragement:在contaiiner中用于指定component所需的数据。
posted @ 2018-09-01 18:40  tutu_python  阅读(136)  评论(0)    收藏  举报