简体   繁体   English

使用Apollo React用GraphQL包装RESTapi

[英]Wrapping a RESTapi with GraphQL using Apollo React

I need to do a project (currency exchange app) using Apollo client and React. 我需要使用Apollo客户端和React做一个项目(货币兑换应用程序)。 I need to wrap an existing REST api (fixer.io) with graphql. 我需要使用graphql包装现有的REST api(fixer.io)。 So far no luck finding a solution online. 到目前为止,在网上找不到解决方案是没有运气的。 Tried several tutorials but they don't seem to work. 尝试了一些教程,但它们似乎不起作用。 Anyone have experience with this? 有人对此有经验吗?

Thanks. 谢谢。

I assume you use Apollo client 2.0 and want everything to be client side. 我假设您使用Apollo客户端2.0,并且希望所有内容都成为客户端。

First you need an apollo bridge link . 首先,您需要一个阿波罗桥链接 It's used "When you don't have GraphQL server (yet) and want to use GraphQL on the client". 它用于“当您还没有GraphQL服务器并且想要在客户端上使用GraphQL时”。 Its source code is quite short, so you can inline it: 它的源代码很短,因此您可以内联它:

/*
  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);
    }
}

Next you create schema and resolvers: 接下来,创建架构和解析器:

// 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;

Finally, you create an apollo client factory: 最后,创建一个阿波罗客户端工厂:

// 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;
};

Here's how you use it: 使用方法如下:

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)

If you want to use it in React: 如果要在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'),
);

With the Graphcool Framework , you can define resolver functions , which allow you to easily wrap any REST API. 使用Graphcool Framework ,您可以定义解析器功能 ,使您可以轻松包装任何REST API。 You can define a function and connect it to a specific mutation or query in your GraphQL Schema. 您可以定义一个函数并将其连接到GraphQL模式中的特定突变或查询。

I prepared a demo, wrapping the fixer API . 我准备了一个演示,包装了fixer API

Try to run this query to get the exchange rates with USD as base, for example: 尝试运行此查询以获取以美元为基础的汇率,例如:

query {
  fixer(
    base: "USD"
  ) {
    base
    date
    eur
    usd
    rub
  }
}

You can build this demo yourself like this: 您可以这样自己构建此演示:

git clone git@github.com:graphcool/templates.git
cd templates/curated/misc/fixer-wrapper
npm install -g graphcool@next
graphcool init
graphcool deploy
graphcool playground

Please feel free to share any improvement you might have in mind, the example is open source . 请随时分享您可能想到的任何改进,该示例是开源的 You can read more about resolvers here . 您可以在此处阅读有关解析器的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM