Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import { graphql } from 'graphql';
  2. import Logger from '../utils/Logger';
  3. import * as fetch from 'isomorphic-fetch';
  4.  
  5. const logger = new Logger('GraphqlClient');
  6.  
  7. interface IResponse<T> {
  8. data: T;
  9. }
  10.  
  11. export default class GraphqlClient {
  12. private static clientInstance: GraphqlClient;
  13.  
  14. constructor(private url, private token) {}
  15.  
  16. query = <Variables, ResponseData>(
  17. query: string,
  18. variables: Variables
  19. ): Promise<IResponse<ResponseData>> => this.doOperation('query', query, variables);
  20.  
  21. mutate = <Variables, Response extends {}>(
  22. mutation: string,
  23. variables: Variables
  24. ): Promise<Response> => this.doOperation('mutation', mutation, variables);
  25.  
  26. public static getClient = () => {
  27. if (!GraphqlClient.clientInstance) {
  28. GraphqlClient.clientInstance = new GraphqlClient(
  29. process.env.GRAPHQL_API,
  30. process.env.ADMIN_TOKEN
  31. );
  32. }
  33.  
  34. return GraphqlClient.clientInstance;
  35. };
  36.  
  37. private doOperation = (
  38. type: 'query' | 'mutation',
  39. operation: string,
  40. variables
  41. ) =>
  42. fetch(this.url, {
  43. method: 'POST',
  44. body: JSON.stringify({
  45. query: operation,
  46. variables: variables
  47. }),
  48. headers: {
  49. Authorization: this.token,
  50. 'content-type': 'application/json'
  51. }
  52. })
  53. .then(res => res.json())
  54. .then(function(body) {
  55. if (body.errors && body.errors.length) {
  56. logger.info(
  57. 'Error running graphql request',
  58. JSON.stringify({ errors: body.errors, operation, variables })
  59. );
  60. throw new Error(body.errors);
  61. }
  62.  
  63. return body;
  64. });
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement