0.1.1 • Published 8 months ago

@grnx-utils/apollo v0.1.1

Weekly downloads
-
License
-
Repository
github
Last release
8 months ago

@grnx-utils/apollo

npm version PRs Welcome

Wrapper over @apollo/client, which makes the syntax cleaner.

For example, instead of this:

const response = await apollo.mutate({
    mutation: gql,
    variables: {
        _graphql: {
            username,
            id
        }
    }
})

const result = response.data.yourMethod

You can do this:

const result = await apollo.request<Res, Body>(gql, { username, id }, 'mutate')

Installation

yarn add @grnx-utils/apollo -D

Usage

// apollo-config.ts
import { createApolloClient } from '@grnx-utils/apollo'

const apollo = createApolloClient({
    url: 'http://localhost:6868',
    /** Enable library logs
     *  @default false
     */ 
    isDev: process.env.NODE_ENV === 'development',
    /** Additions @apollo/client config
     *  @default {}
     */
    extend: {
        queryDeduplication: false
    }
})

Configure API (apollo.request)

const response = await apollo.request<ResponsePayload, RequestBody>(
    /** graphql query
     *  @type {ApolloOperation}
     */
    mutation,
    /** graphql body
     *  @type {Record<string, unknown>}
     */
    { username: 'test' },
    /** graphql method
     *  @type {'query' | 'mutate'}
     *  @default 'query'
     */
    'mutate'
)

Examples

Case with query

// fetch-users.ts
import type { ApolloOperation } from '@grnx-utils/apollo'
import { apollo } from './apollo-config.ts'
import { gql } from 'graphql-tag'

interface User {
    name: string
    id: number
}

const query: ApolloOperation = {
    gql: gql`
    query {
      getUsers {
        name
        id
      }
    }
  `, 
  method: 'getUsers'
}

const users = await apollo.request<User[], void>(query, { page: 0 })

Case with mutation

// delete-user.ts
import { apollo } from './apollo-config.ts'

export interface ApolloBody {
    username: string
}

const mutation: ApolloOperation = {
    gql: gql`
     mutation SignIn($payload: SignIn!) {
      signIn(_graphql: $payload) {
        accessToken
      }
    }
  `,
   method: 'signIn'
}

const payload = await apollo.request<User[], ApolloBody>(mutation, { username: 'test' }, 'mutate')
0.1.1

8 months ago

0.1.0

9 months ago

0.0.1

9 months ago