在React项目中的使用Apollo graphql 客户端

在这里插入图片描述

Apollo Server 是一个 Apollo 开源的一个基于 Nodejs 的 GraphQL 后端服务集成方案。主要提供 GraphQL 后端的数据解析,查询,突变等解析功能,可以提供给任何的 GraphQL 客户端查询。Apollo Client 是一个全功能的 GraphQL 客户端,用于 React 、Angular 的交互。允许你轻松通过 GraphQL 获取数据并构建 UI 组件。

安装

npm install @apollo/client graphql

创建

/**
 * apollo对象
 */
import {
  ApolloClient,
  InMemoryCache,
  createHttpLink,
  gql,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

// 鉴权:在请求头中添加token
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  let userInfo = localStorage.getItem("userInfo")
  let token ="";
  if(userInfo){
    token = JSON.parse(userInfo).accessToken
  }
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});
const URI = 'https://a0502.42.huizhouyiren.com/query'
const httpLink = createHttpLink({
  uri: URI,
});

// 创建apollo 对象
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

export default { client, gql };

使用

query : 查询操作

mutation : 提交操作

import Request from "../../utils/client";
// 获取制造商
export const AQUIRE = Request.gql`
  query getManufacturersQuery{
    getManufacturers{
      id
      isDefault
      name
      remark
    }
  }
`;
// 删除制造商
export const DELETE = Request.gql`
  mutation deleteManufacturerMutation($id: Int!) {
    deleteManufacturer(id: $id) 
  }
`;


  // 请求数据
  aquireData = () => {
    Request.client
      .query({
        query: AQUIRE,
        fetchPolicy: "no-cache",
      })
      .then((result) => {
        console.log("获取制造商",result)
      });
  };
  deleteItem = (item) => {
    console.log(item);
    Request.client
      .mutate({
        mutation: DELETE, // 封装好的GraphQL,
        variables: {
          id: item.id,
        },
      })
      .then((result) => {
        message.success("删除制造商成功");
      })
      .catch((error) => {
        message.error(error.message);
      });
  };

graphql的缓存设置

apollo graphql的提取策略是缓存优先,这意味着它会在发出网络请求之前检查缓存以查看结果是否存在。在请求的过程中往往数据参数没有发生变化的时候都是使用缓存中的内容的,可以通过设置 fetchPolicy属性的值来改变缓存设置

fetchPolicy “cache-first” |“cache-and-network” | “network-only” |“cache-only” | “no-cache” | “standby”.

// 示例
this.$apollo.query({
   query: getQueueByUserName,
   variables: {
     userName: this.Select
   },
   fetchPolicy: 'network-only' // 缓存配置
 })

使用apollo 上传文件

参考文档 : 使用apollop-upload-client上传文件

安装apollo-upload-client
npm install apollo-upload-client

挂载apollo-upload-client

/**
 * apollo对象
 */

import { createUploadLink } from "apollo-upload-client";

import {
  ApolloClient,
} from "@apollo/client";

const URI = 'https://a0502.42.huizhouyiren.com/query'

export const uploadClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: createUploadLink({
    uri: URI,
  }),
});

使用

import Request, { uploadClient } from "../../../../utils/client";

// 上传图片
export const SINGLE_UPLOAD = Request.gql`
  mutation singleUpload($file: Upload!) {
    singleUpload(file: $file) {
      id
      url
    }
  }
`;

 // 自定义logo上传的方法
  let doImgUpload = (options) => {
    // const { onSuccess, onError, file, onProgress } = options;
    // file 是文件对象
    const { file } = options;
    console.log("file", file);
    setLoad(true);
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("图片格式只能是JPG/PNG");
      setLoad(false);
      return;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过2MB!");
      setLoad(false);
      return;
    }
    
    // 上传图片文件
    uploadClient
      .mutate({
        mutation: SINGLE_UPLOAD,
        variables: {
          file,
        },
      })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        message.error(err);
        setLoad(false);
      });
  };
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值