Apollo Graphql 点点滴滴

Apollo Graphql 点点滴滴

  • Apollo Graphql 点点滴滴
    • Generating Types with Apollo CLI

Apollo Graphql 点点滴滴

Generating Types with Apollo CLI

npx apollo service:download \
--endpoint=http://localhost:4000 \
graphql-schema.json

上面的命令用户根据 graphql server endpoint 生成 schema,生成文件名称为 graphql-schema.json

创建 GraphQL queries,创建 src/queries/liftQuery.ts 文件

import { gql } from "apollo-boost";
const liftQuery = gql`
  query AllLifts {
    allLifts {
      id
      name
      status
      capacity
      trailAccess {
        id
        name
        status
      }
    }
  }
`;
export default liftQuery;

根据 graphql schema 生成客户端 types

npx apollo client:codegen \
--localSchemaFile=graphql-schema.json \
--target=typescript \
--includes=src/**/*.ts \
--tagName=gql \
--addTypename \
--globalTypesFile=src/types/graphql-global-types.ts \
types

上面的命令会创建 src/types/graphql-global-types.ts 文件和 src/queries/types/AllLifts.ts 文件

生成的 types 用于 React Component

import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import liftQuery from './queries/liftQuery';
import { AllLifts } from './queries/types/AllLifts';

const App: React.FC<{}> = () => {
  const { loading, data } = useQuery<AllLifts>(liftQuery);

  if (loading) return <p>Loading</p>;

  return (
    <section>
      <h1>SnowTooth Lift Status</h1>

      {data && !loading && (
        <table className="lifts">
          <thead>
            <tr>
              <th>Lift Name</th>
              <th>Current Status</th>
            </tr>
          </thead>
          <tbody>
            {data.allLifts.map((lift) => (
              <tr key={lift.id}>
                <td>{lift.id}</td>
                <td>{lift.status}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </section>
  );
};

export default App;

你可能感兴趣的:(前端)