@fishx/graphql-client
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

@fishx/graphql-client

超轻量GraphQL客户端

安装

npm i @fishx/graphql-client

使用

graphql-client对象 使用

  1. 创建全局的 GraphaqClient.js,保证client对象 全局唯一
import { GraphQLClient } from '@fishx/graphql-client';

const client = new GraphQLClient(`/appcloud/graphql`, {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
});

export default client;
  1. 定义gql services.js
import gql from 'gql-tag';
export const GET_USERS = gql`
{
  findAllAcUsers {
    id
    userNumber
    userName
  }
}
`;

export const GET_ROLES = gql`
{
  roles {
    id
    roleName
    roleDesc
  }
}
`;

export const CREATE_USER_ROLE = gql`
  mutation($userRole: [AcUserRolePkInput!]) {
    newGroupMember(input: $userRole) {
      code
      msg
    }
  }
`;
  1. 使用
import client from '@/utils/GraphqlClient';
import { GET_USERS, GET_ROLES, CREATE_USER_ROLE } from '../services';
  // 查询users
  useEffect(() => {
    client
      .query(GET_USERS)
      .then(res => {
        setUsers(res.findAllAcUsers);
      })
      .catch(res => {
        errorNotification(res);
      });
  }, []);
  // 查询roles
  useEffect(() => {
    client
      .query(GET_ROLES)
      .then(res => {
        setRoles(res.roles);
      })
      .catch(res => {
        errorNotification(res);
      });
  }, []);
  // 创建 user_role对象
  const doAddMember = () => {
    client
      .query(CREATE_USER_ROLE, {
        userRole: [
          {
            userId: userIdSelect.current,
            roleId: roleIdSelect.current,
            groupId,
          },
        ],
      })
      .then(res => {
        // const { newGroupMember: { code, msg } } = res;
        const { newGroupMember: { code } } = res;
        if (code === 1) {
          commonNotification(i18n('COMMON_ADD_FAILURE', { name: i18n('MSG_GROUP_MEMBER') }));
          return;
        }
        if (code === 0) {
          commonSuccessNotification(i18n('COMMON_ADD_SUCCESS', { name: i18n('MSG_GROUP_MEMBER') }));
          updateInfo('true');
        }
      })
      .catch(res => {
        errorNotification(res);
      });
  };

query方法使用

import { query } from '@fishx/graphql-client'
import gql from 'gql-tag' 

const GET_PERSONS = gql`
  {
    allPersons {
      id
      name
    }
  }
`

const endpoint = 'https://api.graph.cool/simple/v1/swapi'

const data = await query(endpoint, GET_PERSONS)

变量

const GET_PERSON = gql`
  query getPerson($id: ID) {
    Person(id: $id) {
      id
      name
    }
  }
`

const data = await query(endpoint, GET_PERSON, {
  id: 'cj0nv9peiewhf013011i9a4h2',
})

注意事项

案例

Readme

Keywords

none

Package Sidebar

Install

npm i @fishx/graphql-client

Weekly Downloads

24

Version

2.0.0

License

none

Unpacked Size

99.1 kB

Total Files

12

Last publish

Collaborators

  • whalecloud-developer