Apollo Boost简介

With as much as we’ve gone over creating APIs with GraphQL and Prisma in previous articles, we’ve never actually applied our custom backend to a client-side app. In this article, you’ll learn how to let your user interact with your backend through queries and mutations using Apollo Boost, a package that gives us everything out of the box to use the Apollo Client.

前面的文章中 ,我们已经尽可能多地使用GraphQL和Prisma创建API,但实际上我们从未将自定义后端应用于客户端应用程序。 在本文中,您将学习如何使用Apollo Boost来让用户通过查询和变异与您的后端交互,该软件包使我们可以立即使用Apollo客户端。

安装 (Installation)

I’m going to try to take a more general approach and use Apollo without any other libraries like React or Vue. So we’re just going to need an HTML and JavaScript file with the parcel bundler to let us use the latest JavaScript features without fumbling around with webpack. Throwing in babel-polyfill will give us access to async/await.

我将尝试采用更通用的方法,并在没有其他任何库(例如React或Vue)的情况下使用Apollo。 因此,我们只需要带有包裹打包器HTML和JavaScript文件,即可使我们使用最新JavaScript功能,而不会弄乱webpack。 放入babel-polyfill将使我们能够访问async / await

$ npm install parcel-bundler apollo-boost graphql babel-polyfill

后端设定 (Backend Setup)

To avoid focusing too much on the backend I’ve made this starter with a few resolvers for you to work with. You’ll need a Heroku account with a Postgres database setup, which you can read up on here, and add the credentials to an env file.

为避免过多地关注后端,我为这个初学者提供了一些解析器供您使用。 您将需要一个具有Postgres数据库设置的Heroku帐户,您可以在此处进行阅读 ,并将凭据添加到一个env文件中。

Just remember to run this and start your project in a separate terminal.

只需记住运行它并在单独的终端中启动项目即可。

$ cd prisma
$ docker-compose up -d 
$ prisma deploy 
$ cd ../
$ yarn get-schema 
$ yarn start

Or if you don’t want to fumble around with a custom backend, I recommend checking out GraphCMS and creating a post model to play with.

或者,如果您不想随意使用自定义后端,我建议您检查GraphCMS并创建一个可以使用的帖子模型。

查询 (Queries)

Connecting to our backend couldn’t be simpler, just toss in our URI to ApolloBoost and you’ll be all hooked up. If you’ve ever worked with Gatsby before, you’re should already be very familiar with the gql tag function. With gql and some backtics we can structure our requests exactly how we would in GraphQL Playground.

连接到我们的后端再简单不过了,只需将我们的URI ApolloBoost ,您就会被吸引住。 如果您曾经使用过Gatsby,那么您应该已经非常熟悉gql标签功能。 借助gql和一些支持,我们可以像在GraphQL Playground中一样精确地构造请求。

Now our server’s query method will take our request and return a promise. Pushing everything into a div will do for rendering. Keep in mind that this is still all front-end code, so we access DOM elements directly.

现在,我们服务器的query方法将接受我们的请求并返回一个Promise。 将所有内容推入div进行渲染。 请记住,这仍然是所有前端代码,因此我们直接访问DOM元素。

index.js
index.js
import "babel-polyfill";
import ApolloBoost, { gql } from 'apollo-boost';

const server = new ApolloBoost({
  uri: 'http://localhost:4000/' // Or to you GraphCMS API
});

const query = gql`
  query {    
    posts {
      title 
      body
    }
  }
`;

const render = posts => {
  let html = '';

  posts.data.posts.forEach(post => {
    html += `
      <div>
      <h3>${post.title}</h3>
      <p>${post.body}</p>
      </div>
    `;
  });
  document.querySelector('#posts').innerHTML = html;
};

const getPosts = async query => {
  const server = new ApolloBoost({ uri: 'http://localhost:4000/' });

  const posts = await server.query({ query });
  render(posts);
};

getPosts(query);
index.html
index.html
<body>
  <div id="posts"></div>
</body>

变异 (Mutations)

Mutations are just as easy as you would imagine, just make your mutation as you normally would and pass it to the server’s mutate method. We can even submit data with our form without setting up a standard server, since this is all client-side already.

突变就像您想象的一样容易,只需像平常一样进行突变,然后将其传递给服务器的mutate方法即可。 我们甚至可以通过表单提交数据而无需设置标准服务器,因为这已经是所有客户端了。

index.html
index.html
<body>
  <form id="form">
    <input type="text" name="title" placeholder="Title" />
    <input type="text" name="body" placeholder="Body" >
    <div class="controls">
      <button type="submit" id="submit">Submit</button>
      <button type="button" id="clearPosts">Clear All</button>
    </div>
    </form>

  <div id="posts"></div>
</body>
index.js
index.js
const addPost = async data => {
  const mutation = gql`
    mutation {
      addPost(data: {
        title: "${data.title}",
        body: "${data.body}"
      }) {
        title
      }
    }
  `;

  await server.mutate({ mutation });
  getPosts(query);
};

const submit = document.querySelector('#submit');
const form = document.querySelector('#form');

submit.addEventListener('click', e => {
  e.preventDefault()

  addPost({
    title: form.elements.title.value,
    body: form.elements.body.value
  })

  form.reset()
});
const clearAll = async () => {
  const mutation = gql`
  mutation {
    clearPosts {
      count
    }
  }`;

  const count = await server.mutate({ mutation });
  console.log(`${count.data.clearPosts.count} item removed`);
  getPosts(query);
};

const clearBtn = document.querySelector('#clearPosts');
clearBtn.addEventListener('click', () => clearAll());

总结思想 (Closing Thoughts)

Sadly, Apollo Boost really doesn’t help us much with subscriptions, which turns out to be a significantly more complicated process. But overall, Apollo Client makes messing around with fetch requests seem like working with smoke signals 🔥.

可悲的是,Apollo Boost确实对订阅没有太大帮助,事实证明这是一个非常复杂的过程。 但是总的来说,Apollo Client使获取请求变得混乱,就像处理烟雾信号一样。

翻译自: https://www.digitalocean.com/community/tutorials/graphql-apollo-boost-introduction

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值