graphql.js 958 B

12345678910111213141516171819202122232425262728293031323334
  1. import { GraphqlError } from "./error";
  2. const NON_VARIABLE_OPTIONS = [
  3. "method",
  4. "baseUrl",
  5. "url",
  6. "headers",
  7. "request",
  8. "query"
  9. ];
  10. export function graphql(request, query, options) {
  11. options =
  12. typeof query === "string"
  13. ? (options = Object.assign({ query }, options))
  14. : (options = query);
  15. const requestOptions = Object.keys(options).reduce((result, key) => {
  16. if (NON_VARIABLE_OPTIONS.includes(key)) {
  17. result[key] = options[key];
  18. return result;
  19. }
  20. if (!result.variables) {
  21. result.variables = {};
  22. }
  23. result.variables[key] = options[key];
  24. return result;
  25. }, {});
  26. return request(requestOptions).then(response => {
  27. if (response.data.errors) {
  28. throw new GraphqlError(requestOptions, {
  29. data: response.data
  30. });
  31. }
  32. return response.data.data;
  33. });
  34. }