Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { graphql } from 'graphql';
- import Logger from '../utils/Logger';
- import * as fetch from 'isomorphic-fetch';
- const logger = new Logger('GraphqlClient');
- interface IResponse<T> {
- data: T;
- }
- export default class GraphqlClient {
- private static clientInstance: GraphqlClient;
- constructor(private url, private token) {}
- query = <Variables, ResponseData>(
- query: string,
- variables: Variables
- ): Promise<IResponse<ResponseData>> => this.doOperation('query', query, variables);
- mutate = <Variables, Response extends {}>(
- mutation: string,
- variables: Variables
- ): Promise<Response> => this.doOperation('mutation', mutation, variables);
- public static getClient = () => {
- if (!GraphqlClient.clientInstance) {
- GraphqlClient.clientInstance = new GraphqlClient(
- process.env.GRAPHQL_API,
- process.env.ADMIN_TOKEN
- );
- }
- return GraphqlClient.clientInstance;
- };
- private doOperation = (
- type: 'query' | 'mutation',
- operation: string,
- variables
- ) =>
- fetch(this.url, {
- method: 'POST',
- body: JSON.stringify({
- query: operation,
- variables: variables
- }),
- headers: {
- Authorization: this.token,
- 'content-type': 'application/json'
- }
- })
- .then(res => res.json())
- .then(function(body) {
- if (body.errors && body.errors.length) {
- logger.info(
- 'Error running graphql request',
- JSON.stringify({ errors: body.errors, operation, variables })
- );
- throw new Error(body.errors);
- }
- return body;
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement