Skip to content

Instantly share code, notes, and snippets.

@etc-tiago
Created May 5, 2020 02:18
Show Gist options
  • Save etc-tiago/9c03934523c166f7e81e99d97f5c06a7 to your computer and use it in GitHub Desktop.
Save etc-tiago/9c03934523c166f7e81e99d97f5c06a7 to your computer and use it in GitHub Desktop.

Use React Relay

Document in pt-br to explanation the sequencies of commands for build graphql client with relay and CRA.

Instalação do relay

react-relay - O pacote que permite usar relay no projeto react.

relay-compiler - Pacote de desenvolvimento que permite compilar o código graphql estatico.

babel-plugin-relay - Pacote de desenvolvimento usado para otimizar o projeto (aqui o eject entra).

graphql - Pacote usado para compilar a schema com o babel.

relay-config - Pacote para executar a configuração em um arquivo relay.config.js

get-graphql-schema - Pacote que transforma a schema do server em um arquivo.

Instale com: yarn add react-relay && yarn add -D relay-compiler babel-plugin-relay relay-config get-graphql-schema graphql

Configuração inicial do Relay

const { Environment, Network, RecordSource, Store } = require("relay-runtime");

// Configura um novo store para armazenamento
const store = new Store(new RecordSource());

// Configura a rede para buscar dados de um endpoint
const network = Network.create((operation, valiables) => {
  return fetch("__RELAY_API_ENDPOINT__", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query: operation.text, valiables }),
  }).then((response) => {
    return response.json();
  });
});

// Configura o ambiente juntando as configuraões de rede e store
const environment = new Environment({ network, store });

module.exports = environment;

Baixe o esquema do servidor graphqlql

get-graphql-schema http://localhost:4000 > src/schema.graphql

Adicione a configuração relay.config.js

module.exports = {
  src: './src',
  schema: './src/schema.graphql',
  exclude: ['**/node_modules/**', '**/__mocks__/**', '**/__generated__/**'],
};

Adicione a configuração do babel

No arquivo .babelrc, adicione:

{
  "presets": ["react-app"],
  "plugins": ["relay"]
}

No package.json, adicione:

{
  "scripts": {
    "get-schema": "get-graphql-schema http://localhost:4000 > ./schema.graphql",
    "relay": "relay-compiler --src ./src --schema ./schema.graphql"
  }
}

Typescript

Se você está usando typescript, instale o relay-compiler-language-typescript como dependencia de desenvolvinento e adapte o script do relay:

{
  "scripts": {
    "relay": "relay-compiler --src ./src --schema ./schema.graphql --extensions ts tsx js jsx --language typescript"
  }
}

Referencias:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment