index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { request } from '@octokit/request';
  2. import { getUserAgent } from 'universal-user-agent';
  3. const VERSION = "4.3.1";
  4. class GraphqlError extends Error {
  5. constructor(request, response) {
  6. const message = response.data.errors[0].message;
  7. super(message);
  8. Object.assign(this, response.data);
  9. this.name = "GraphqlError";
  10. this.request = request;
  11. // Maintains proper stack trace (only available on V8)
  12. /* istanbul ignore next */
  13. if (Error.captureStackTrace) {
  14. Error.captureStackTrace(this, this.constructor);
  15. }
  16. }
  17. }
  18. const NON_VARIABLE_OPTIONS = [
  19. "method",
  20. "baseUrl",
  21. "url",
  22. "headers",
  23. "request",
  24. "query"
  25. ];
  26. function graphql(request, query, options) {
  27. options =
  28. typeof query === "string"
  29. ? (options = Object.assign({ query }, options))
  30. : (options = query);
  31. const requestOptions = Object.keys(options).reduce((result, key) => {
  32. if (NON_VARIABLE_OPTIONS.includes(key)) {
  33. result[key] = options[key];
  34. return result;
  35. }
  36. if (!result.variables) {
  37. result.variables = {};
  38. }
  39. result.variables[key] = options[key];
  40. return result;
  41. }, {});
  42. return request(requestOptions).then(response => {
  43. if (response.data.errors) {
  44. throw new GraphqlError(requestOptions, {
  45. data: response.data
  46. });
  47. }
  48. return response.data.data;
  49. });
  50. }
  51. function withDefaults(request$1, newDefaults) {
  52. const newRequest = request$1.defaults(newDefaults);
  53. const newApi = (query, options) => {
  54. return graphql(newRequest, query, options);
  55. };
  56. return Object.assign(newApi, {
  57. defaults: withDefaults.bind(null, newRequest),
  58. endpoint: request.endpoint
  59. });
  60. }
  61. const graphql$1 = withDefaults(request, {
  62. headers: {
  63. "user-agent": `octokit-graphql.js/${VERSION} ${getUserAgent()}`
  64. },
  65. method: "POST",
  66. url: "/graphql"
  67. });
  68. function withCustomRequest(customRequest) {
  69. return withDefaults(customRequest, {
  70. method: "POST",
  71. url: "/graphql"
  72. });
  73. }
  74. export { graphql$1 as graphql, withCustomRequest };
  75. //# sourceMappingURL=index.js.map