Apollo Boost简介

news/2024/7/3 5:49:34

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


http://www.niftyadmin.cn/n/3648859.html

相关文章

成就Android英才之路

著作权归作者所有。商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处。作者&#xff1a;王宇龙链接&#xff1a;http://www.zhihu.com/question/19759722/answer/29213925来源&#xff1a;知乎由于工作需要大量修改framework代码, 在AOSP(Android Open Source Proj…

如何设计架构?

axing&#xff08;转载自www.Linuxaid.com.cn&#xff09;  2003年05月04日 Part 1 层 层&#xff08;layer&#xff09;这个概念在计算机领域是非常了不得的一个概念。计算机本身就体现了一种层的概念&#xff1a;系统调用层、设备驱动层、操作系统层、CPU指令集。每个层都负…

baseActivity的封装——模板式设计模式

public abstract class BaseActivity extends AppCompatActivity {Overrideprotected void onCreate(Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);//初始化布局setContentView();// 一些特定的算法&#xff0c;子类基本都会使用的(比如butterkni…

使用Visual Studio Code和ESLint进行保存

We need style guides to write consistent, reusable and clean code. But when you have been working 10 hours a day on a project for the past 3 months it’s hard to notice an extra indentation in your code or a single quote instead of a double quote. 我们需要…

Git使用教程详解之一 Git起步

起步 本章介绍开始使用 Git 前的相关知识。我们会先了解一些版本控制工具的历史背景&#xff0c;然后试着让 Git 在你的系统上跑起来&#xff0c;直到最后配置好&#xff0c;可以正常开始开发工作。读完本章&#xff0c;你就会明白为什么 Git 会如此流行&#xff0c;为什么你应…

网络引擎与数据库相结合

结合之前两篇文章链式调用打造第三方的网络引擎 http://blog.csdn.net/qq_24675479/article/details/79277616 和 自己动手搭建数据库框架 http://blog.csdn.net/qq_24675479/article/details/79285849 首先逻辑处理:每次都会请求数据&#xff0c;但是为了保证用户体验&…

css伪类选择器_如何使用CSS:root伪类选择器

css伪类选择器Learn about the CSS :root pseudo-class selector, and how you might want to use it in your projects! 了解CSS :root伪类选择器&#xff0c;以及如何在项目中使用它&#xff01; The CSS :root pseudo-class selector is used to select the highest-level …

Git使用教程详解之二 Git基础

Git 基础 读完本章你就能上手使用 Git 了。本章将介绍几个最基本的&#xff0c;也是最常用的 Git 命令&#xff0c;以后绝大多数时间里用到的也就是这几个命令。读完本章&#xff0c;你就能初始化一个新的代码仓库&#xff0c;做一些适当配置&#xff1b;开始或停止跟踪某些文件…