博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Apollo Boost简介
阅读量:2509 次
发布时间:2019-05-11

本文共 4773 字,大约阅读时间需要 15 分钟。

With as much as we’ve gone over creating APIs with GraphQL and Prisma in , 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 , a package that gives us everything out of the box to use the Apollo Client.

在 ,我们已经尽可能多地使用GraphQL和Prisma创建API,但实际上我们从未将自定义后端应用于客户端应用程序。 在本文中,您将学习如何使用来让用户通过查询和变异与您的后端交互,该软件包使我们可以立即使用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 to let us use the latest JavaScript features without fumbling around with webpack. Throwing in babel-polyfill will give us access to .

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

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

后端设定 (Backend Setup)

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

为避免过多地关注后端,我为提供了一些解析器供您使用。 您将需要一个具有Postgres数据库设置的帐户,您可以进行 ,并将凭据添加到一个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 and creating a post model to play with.

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

查询 (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 += `      

${post.title}

${post.body}

`; }); 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
  

变异 (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
  
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 requests seem like working with smoke signals 🔥.

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

翻译自:

转载地址:http://hphgb.baihongyu.com/

你可能感兴趣的文章
从Vue.js窥探前端行业
查看>>
学习进度
查看>>
poj3368 RMQ
查看>>
“此人不存在”
查看>>
github.com加速节点
查看>>
解密zend-PHP凤凰源码程序
查看>>
python3 序列分片记录
查看>>
Atitit.git的存储结构and 追踪
查看>>
atitit 读书与获取知识资料的attilax的总结.docx
查看>>
B站 React教程笔记day2(3)React-Redux
查看>>
找了一个api管理工具
查看>>
C++——string类和标准模板库
查看>>
zt C++ list 类学习笔记
查看>>
git常用命令
查看>>
探讨和比较Java和_NET的序列化_Serialization_框架
查看>>
1、jQuery概述
查看>>
数组比较大小的几种方法及math是方法
查看>>
FTP站点建立 普通电脑版&&服务器版
查看>>
js 给一段代码,给出运行后的最终结果的一些综合情况、
查看>>
webservice 详解
查看>>