1.0.1 • Published 3 years ago

graphql-request-helper v1.0.1

Weekly downloads
30
License
MIT
Repository
github
Last release
3 years ago

graphql-request-helper

Helper Class of Graphql Client

Getting Started

Installing

$ npm install graphql-request-helper

Usage

import { GraphQLClient } from "graphql-request-helper";

Create Graphql Client

const graphQLClient = new GraphQLClient("http://localhost:3000/api/graphql");

Performing a Query request

const data = await graphQLClient.query({
  name: "getAnimals",
  fields: [
    "id",
    "name",
    "age",
    {
      name: "family",
      fields: ["id", "name"],
    },
  ],
  params: {
    age: 3,
  },
});

GraphQLClient receives the above fields and params and sends the following request

query{
    getAnimals(age: 3){
        id
        name
        age
        family{
            id
            name
        }
    }
}

Performing a Mutation request

const data = await graphQLClient.mutation({
  name: "addAnimal",
  fields: [
    "id",
    "name",
    "age",
    {
      name: "family",
      fields: ["id", "name"],
    },
  ],
  params: {
    name: "puppy",
    age: 1,
    isCute: true,
  },
});

GraphQLClient receives the above fields and params and sends the following request

mutation{
    addAnimal(name: "puppy", age: 1, isCute: true){
        id
        name
        age
        family{
            id
            name
        }
    }
}

Catch an Error

import { GraphQLError } from "graphql-request-helper";
try {
  const data = await graphQLClient.query({
    // ...
  });
} catch (e) {
  if (e instanceof GraphQLError) {
    console.log(e.errors);
  }
}

then e.errors will be like this

[
  {
    "message": "Schema is not configured for mutations.",
    "locations": [
      {
        "line": 1,
        "column": 1
      }
    ]
  }
]

use axios options

const graphQLClient = new GraphQLClient("http://localhost:3000/api/graphql", {
  axios: {
    headers: {
      Authorization: "Bearer ...",
    },
  },
});

The axios option is used as the third parameter in the axios request

constructor(url, options) {
  this.axiosOptions = options?.axios
}
// ...
const response = await axios.post(
  this.graphQLUrl,
  {
    query,
  },
  this.axiosOptions
);

You can also modify it as a setAxiosOptions function.

const graphQLClient = new GraphQLClient("http://localhost:3000/api/graphql", {
  axios: {
    headers: {
      Authorization: "Bearer A",
    },
  },
});

graphQLClient.setAxiosOptions({
  headers: {
    Authorization: "Bearer B",
  },
});
1.0.1

3 years ago

1.0.0

3 years ago

0.2.2

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.9

3 years ago

0.1.8

3 years ago

0.1.7

3 years ago

0.1.6

3 years ago

0.1.5

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago