javascript – 使用Apollo React使用GraphQL包装RESTapi

我需要使用Apollo客户端和React做一个项目(货币兑换应用程序).我需要用graphql包装一个现有的REST api(fixer.io).到目前为止,没有运气在线找到解决方案试过几个教程,但它们似乎不起作用.有人有这方面的经验吗?

谢谢.

解决方法:

我假设您使用Apollo client 2.0并希望一切都是客户端.

首先你需要一个apollo bridge link.它用于“当你还没有GraphQL服务器(还)并希望在客户端使用GraphQL”时.它的源代码很短,所以你可以内联它:

/*
  Copyright (c) 2017 David Cizek
  https://github.com/dacz/apollo-bridge-link
*/
import { GraphQLSchema, graphql, print } from 'graphql';
import { addMockFunctionsToSchema, makeExecutableSchema } from 'graphql-tools';

import { ApolloLink } from 'apollo-link';
import Observable from 'zen-observable';

export const createBridgeLink = ({ schema, resolvers, mock, context = {} }) => {
    let executableSchema;
    if (typeof schema === 'string') {
        executableSchema = makeExecutableSchema({ typeDefs: schema, resolvers });
    } else if (schema.kind === 'Document') {
        executableSchema = makeExecutableSchema({
            typeDefs: print(schema),
            resolvers,
        });
    } else if (schema instanceof GraphQLSchema) {
        executableSchema = schema;
    } else {
        throw new Error('schema should be plain text, parsed schema or executable schema.');
    }

    if (mock)
        {addMockFunctionsToSchema({
            schema: executableSchema,
            preserveResolvers: true,
        });}

    return new ApolloLink(
        operation =>
            new Observable(observer => {
                const { headers, credentials } = operation.getContext();
                const ctx = {
                    ...context,
                    headers,
                    credentials,
                };

                graphql(executableSchema, print(operation.query), undefined, ctx, operation.variables, operation.operationName)
                    .then(data => {
                        observer.next(data);
                        observer.complete();
                    })
                    .catch(err => {
                        /* istanbul ignore next */
                        observer.error(err);
                    });
            }),
    );
};

export class BridgeLink extends ApolloLink {
    requester;

    constructor(opts) {
        super();
        this.requester = createBridgeLink(opts).request;
    }

    request(op) {
        return this.requester(op);
    }
}

接下来,您将创建架构和解析器:

// schema.js
export default `
type Rate {
  date: Date!
  rate: Float!
}

type Query {
  latestRate(from: String!, to: String!): Rate
}

schema {
  query: Query
}
`;


// resolvers.js
const resolvers = {
  Query: {
    latestRate(obj, args, context, info) {
      return fetch(`https://api.fixer.io/latest?base=${args.from}`).then(res => res.json())
      .then(res => { date: res.date, rate: res.rates[args.to] })
    }
  }
}

export default resolvers;

最后,创建一个apollo客户端工厂:

// clientFactory.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

import { BridgeLink } from './apollo-bridge-link';

import schema from './schema';
import resolvers from './resolvers';

export default () => {
    const mock = false;
    const context = {};

    const client = new ApolloClient({
        link: new BridgeLink({ schema, resolvers, mock, context }),
        cache: new InMemoryCache(),
    });
    return client;
};

以下是您使用它的方式:

import gql from 'graphql-tag';
import clientFactory from './clientFactory'

const client = clientFactory();

client.query(gql`query {
  latestRate(from: "USD", to: "EUR") { date, rate }
}`).then(console.log)

如果你想在React中使用它:

import { ApolloProvider } from 'react-apollo';
const client = clientFactory();

const App = ({ data: { latestRate, refetch } }) => {
  return <div>
    <span>Today:</span><span>{latestRate.date}</span>
    <span>1 USD equals:</span><span>{latestRate.rate} EUR</span>
    <button onClick={() => refetch()}>
      Refresh
    </button>
  </div>
}

const AppWithQuery = graphql(gql`
  query {
    latestRate(from: "USD", to: "EUR") { date, rate }
  }
`)(App);

ReactDOM.render(
  <ApolloProvider client={client}>
    <AppWithQuery/>
  </ApolloProvider>,
  document.getElementById('root'),
);
上一篇:5个用/不用GraphQL的理由


下一篇:GraphQL 在酒店系统上的实践