GraphQL - 不使用挂钩的 Apollo 客户端?

GraphQL - Apollo Client without using hooks?

我正在尝试将 Apollo GraphQL 客户端用于 React Native。但是,在我的应用程序的某些部分,我需要对 GraphQL 数据进行更改,这样界面就不会暴露给用户。

例如,在我的注册页面上,我想在数据库中创建一个用户,但前提是我已经完成并验证了所有内容,创建了一个 uuid 等(需要 class).如果调用成功,我想立即转到应用程序的主页。如果没有,我想通知用户。

因此,我需要访问权限来执行 GraphQL 请求,无需挂钩,只需使用回调来更改 UI。这可能吗?如何实现?

是的,有可能。

对 GraphQL 服务的调用只需要正文中的 querymutation 键值对以及您尝试发送的 query/mutation。

您可以使用简单的 fetch 请求 POSTcURL 或通过邮递员来完成此操作...只要它是POST请求。

See also here.

文档没有很好地解释它,但您可以简单地在 ApolloClient 对象上调用 querymutatehttps://www.apollographql.com/docs/react/api/core/ApolloClient/#apolloclient-functions

与其他答案相比,这可能比仅使用 fetch 进行原始调用更好,因为它使用与应用程序其余部分相同的缓存层,而不是绕过它。

const apolloClient = new ApolloClient({
    uri: "/graphql",
    cache: new InMemoryCache()
})

const qr = gql`
    query {
       getCustomers() {
           name
       }
    }
`
const result = await apolloClient.query({
    query: qr ,
    variables: {}
})

是的,事实上我可能会留下样本 classes 可用于查询和变异。

首先,配置您的应用程序以使用 graphQl。 使用提供商包装您的应用。

import { client } from './config/connection';
import { ApolloProvider } from '@apollo/client';

<ApolloProvider client={client}>
  <App/>
</ApolloProvider>

这是我们想要的客户端

import { ApolloClient, ApolloLink, InMemoryCache } from '@apollo/client';

export const client = new ApolloClient({
  cache: new InMemoryCache(),
  uri: 'http://localhost:4000/graphql',
});

Operations.js(包含查询和变更 gql)

import { gql } from '@apollo/client';

export const Query_SignIn = gql`
  query Login($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      name
    }
  }
`;

export const Mutate_SignUp = gql`
  mutation SignUp($name: String!, $email: String!, $password: String!, $passwordConfirmation: String!) {
    signUp(name: $name, email: $email, password: $password, passwordConfirmation: $passwordConfirmation) {
      name
    }
  }
`;

A Class 使用查询而不是 useQuery 钩子

import { Query_SignIn } from '../../../operations';
class login {
  constructor(client) {
    this._client = client;
  }

  async signIn(email, password) {
    const response = await this._client.query({
      query: Query_SignIn,
      variables: {
        email,
        password,
      },
    });

    return response;
  }
}

export default login;

A class 使用 mutate 而不是 useMutation

import { Mutate_SignUp } from '../../../operations';
class register {
  constructor(client) {
    this._client = client;
  }

  async signUp(accountType, name, email, password, passwordConfirmation) {
    const response = await this._client.mutate({
      mutation: Mutate_SignUp,
      variables: {
        name,
        email,
        password,
        passwordConfirmation,
      },
    });

    return response;
  }
}

export default register;