WrapQuery.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var __assign = (this && this.__assign) || function () {
  2. __assign = Object.assign || function(t) {
  3. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4. s = arguments[i];
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6. t[p] = s[p];
  7. }
  8. return t;
  9. };
  10. return __assign.apply(this, arguments);
  11. };
  12. var __spreadArrays = (this && this.__spreadArrays) || function () {
  13. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  14. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  15. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  16. r[k] = a[j];
  17. return r;
  18. };
  19. Object.defineProperty(exports, "__esModule", { value: true });
  20. var graphql_1 = require("graphql");
  21. var WrapQuery = /** @class */ (function () {
  22. function WrapQuery(path, wrapper, extractor) {
  23. this.path = path;
  24. this.wrapper = wrapper;
  25. this.extractor = extractor;
  26. }
  27. WrapQuery.prototype.transformRequest = function (originalRequest) {
  28. var _a;
  29. var _this = this;
  30. var document = originalRequest.document;
  31. var fieldPath = [];
  32. var ourPath = JSON.stringify(this.path);
  33. var newDocument = graphql_1.visit(document, (_a = {},
  34. _a[graphql_1.Kind.FIELD] = {
  35. enter: function (node) {
  36. fieldPath.push(node.name.value);
  37. if (ourPath === JSON.stringify(fieldPath)) {
  38. var wrapResult = _this.wrapper(node.selectionSet);
  39. // Selection can be either a single selection or a selection set. If it's just one selection,
  40. // let's wrap it in a selection set. Otherwise, keep it as is.
  41. var selectionSet = wrapResult.kind === graphql_1.Kind.SELECTION_SET
  42. ? wrapResult
  43. : {
  44. kind: graphql_1.Kind.SELECTION_SET,
  45. selections: [wrapResult]
  46. };
  47. return __assign(__assign({}, node), { selectionSet: selectionSet });
  48. }
  49. },
  50. leave: function (node) {
  51. fieldPath.pop();
  52. }
  53. },
  54. _a));
  55. return __assign(__assign({}, originalRequest), { document: newDocument });
  56. };
  57. WrapQuery.prototype.transformResult = function (originalResult) {
  58. var rootData = originalResult.data;
  59. if (rootData) {
  60. var data = rootData;
  61. var path = __spreadArrays(this.path);
  62. while (path.length > 1) {
  63. var next = path.shift();
  64. if (data[next]) {
  65. data = data[next];
  66. }
  67. }
  68. data[path[0]] = this.extractor(data[path[0]]);
  69. }
  70. return {
  71. data: rootData,
  72. errors: originalResult.errors
  73. };
  74. };
  75. return WrapQuery;
  76. }());
  77. exports.default = WrapQuery;
  78. //# sourceMappingURL=WrapQuery.js.map