0.0.5 • Published 2 years ago

graphql-client-hybrid v0.0.5

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

graphql-client-hybrid

Instalação

npm install graphql-client-hybrid axios

Como usar

Hybrid

Irá detectar automaticamente se é um browser e configurar o cliente.

import {createClient} from 'graphql-client-hybrid'

const client = createClient({
    endpoint: 'https://api.github.com/graphql',
    headers: {
        authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
    },
})

NodeJs

Para utilizar no NodeJs, é necessário instalar o pacote axios responsável por fazer as requisições.

import {GraphQLClientNode} from 'graphql-client-hybrid/node'

const client = new GraphQLClientNode({
    endpoint: 'https://api.github.com/graphql',
    headers: {
        authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
    },
})

Remix

Para utilizar no lado servidor é necessário instalar o pacote axios responsável por fazer as requisições.

Recomendo utilizar o pacote remix-multipart-formdata-stream para tratar requisições com upload de arquivos.

File: sample.server.ts

import {GraphQLClientNode, gql} from "graphql-client-hybrid";

export const gqlClient = new GraphQLClientNode({
    endpoint: 'https://api.sample.com/graphql',
    headers: {
        authorization: `Bearer ${process.env.API_TOKEN}`,
    },
})

File: sample.ts

import {FileStream, generateFormStream} from "remix-multipart-formdata-stream";
import {gql} from "graphql-client-hybrid";

import {gqlClient} from "~/sample.server";

type ActionData = {
    result?: any;
};

type InputData = {
    username: string;
    file: FileStream;
};

export const MUTATION_USER_UPLOAD = gql`
    mutation ($file: Upload!, $text: String) {
        userUpload(file: $file, text: $text) {
            message
        }
    }
`;

export const action: ActionFunction = async ({request}) => {
    const variables = await generateFormStream<InputData>(request);
    const result = await gqlClient.request(MUTATION_USER_UPLOAD, variables, {
        headers: {
            'X-Custom': "custom",
        }
    });

    return json({result});
}

Inspiração

Esta lib foi baseada no projeto lynxtaa/awesome-graphql-client.