fetchero
Version:
_A type-safe, proxy-based HTTP & GraphQL client for modern applications._
914 lines (899 loc) • 30.9 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var axios = _interopDefault(require('axios'));
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
writable: !1
}), e;
}
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
function _regenerator() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,
t,
r = "function" == typeof Symbol ? Symbol : {},
n = r.iterator || "@@iterator",
o = r.toStringTag || "@@toStringTag";
function i(r, n, o, i) {
var c = n && n.prototype instanceof Generator ? n : Generator,
u = Object.create(c.prototype);
return _regeneratorDefine(u, "_invoke", function (r, n, o) {
var i,
c,
u,
f = 0,
p = o || [],
y = !1,
G = {
p: 0,
n: 0,
v: e,
a: d,
f: d.bind(e, 4),
d: function (t, r) {
return i = t, c = 0, u = e, G.n = r, a;
}
};
function d(r, n) {
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
var o,
i = p[t],
d = G.p,
l = i[2];
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
}
if (o || r > 1) return a;
throw y = !0, n;
}
return function (o, p, l) {
if (f > 1) throw TypeError("Generator is already running");
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
try {
if (f = 2, i) {
if (c || (o = "next"), t = i[o]) {
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
if (!t.done) return t;
u = t.value, c < 2 && (c = 0);
} else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
i = e;
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
} catch (t) {
i = e, c = 1, u = t;
} finally {
f = 1;
}
}
return {
value: t,
done: y
};
};
}(r, o, i), !0), u;
}
var a = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
t = Object.getPrototypeOf;
var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
return this;
}), t),
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
function f(e) {
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
return this;
}), _regeneratorDefine(u, "toString", function () {
return "[object Generator]";
}), (_regenerator = function () {
return {
w: i,
m: f
};
})();
}
function _regeneratorDefine(e, r, n, t) {
var i = Object.defineProperty;
try {
i({}, "", {});
} catch (e) {
i = 0;
}
_regeneratorDefine = function (e, r, n, t) {
if (r) i ? i(e, r, {
value: n,
enumerable: !t,
configurable: !t,
writable: !t
}) : e[r] = n;else {
function o(r, n) {
_regeneratorDefine(e, r, function (e) {
return this._invoke(r, n, e);
});
}
o("next", 0), o("throw", 1), o("return", 2);
}
}, _regeneratorDefine(e, r, n, t);
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
/**
* Utility class for error handling and formatting
*/
var ErrorHandler = /*#__PURE__*/function () {
function ErrorHandler() {}
/**
* Checks if the error indicates a "not found" status
*/
ErrorHandler.isNotFound = function isNotFound(errors) {
var _errors$;
return (errors == null || (_errors$ = errors[0]) == null || (_errors$ = _errors$.extensions) == null ? void 0 : _errors$.code) === '404';
}
/**
* Formats error code with proper structure
*/;
ErrorHandler.formatErrorCode = function formatErrorCode(_ref) {
var code = _ref.code,
extensions = _ref.extensions,
message = _ref.message;
return {
message: message,
extensions: _extends({
code: code
}, extensions)
};
}
/**
* Formats error message structure
*/;
ErrorHandler.formatErrorMessage = function formatErrorMessage(_ref2) {
var extensions = _ref2.extensions,
message = _ref2.message;
return {
extensions: _extends({
message: message
}, extensions)
};
}
/**
* Formats complete error response with default messages
*/;
ErrorHandler.formatErrorResponse = function formatErrorResponse(_ref3) {
var extensions = _ref3.extensions;
var code = extensions.code,
_extensions$message = extensions.message,
message = _extensions$message === void 0 ? '' : _extensions$message;
// Handle 422 errors with object messages
var processedMessage = message;
if (code === '422' && typeof message === 'object' && message !== null) {
processedMessage = Object.values(message).join(', ');
}
var defaultMessages = {
401: message,
404: message,
500: message,
422: processedMessage,
BAD_USER_INPUT: 'Input is not valid',
INTERNAL_SERVER_ERROR: 'Internal Server Error'
};
return {
extensions: {
code: code,
message: code ? defaultMessages[code] || 'Unknown error' : ''
}
};
}
/**
* Composes error formatting functions
*/;
ErrorHandler.compose = function compose(error) {
var _this = this;
var formatters = [this.formatErrorCode, this.formatErrorMessage, this.formatErrorResponse];
return formatters.reduce(function (acc, formatter) {
return formatter === _this.formatErrorCode ? formatter({
code: acc.extensions.code || '',
extensions: acc.extensions,
message: acc.extensions.message || ''
}) : formatter(acc);
}, error);
}
/**
* Creates standardized error response
*/;
ErrorHandler.makeErrorResponse = function makeErrorResponse(_ref4) {
var code = _ref4.code,
message = _ref4.message;
return {
message: 'Internal Server Error',
extensions: {
message: message,
error: true,
code: String(code)
}
};
};
return ErrorHandler;
}();
/**
* Utility class for URL construction
*/
var URLBuilder = /*#__PURE__*/function () {
function URLBuilder() {}
/**
* Builds URL with segments and query parameters
*/
URLBuilder.build = function build(base, segments, query) {
// Validate base URL
if (!base || typeof base !== 'string') {
throw new Error('Base URL must be a non-empty string');
}
try {
var url = new URL(segments.join('/'), base);
if (query && Object.keys(query).length > 0) {
Object.entries(query).forEach(function (_ref) {
var key = _ref[0],
value = _ref[1];
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value));
}
});
}
return url.toString();
} catch (error) {
throw new Error("Invalid URL construction: " + (error instanceof Error ? error.message : 'Unknown error'));
}
};
return URLBuilder;
}();
/**
* Input validation utilities
*/
var Validators = /*#__PURE__*/function () {
function Validators() {}
/**
* Validates URL format
*/
Validators.validateUrl = function validateUrl(url) {
try {
new URL(url);
} catch (_unused) {
throw new Error("Invalid URL format: " + url);
}
}
/**
* Validates headers object
*/;
Validators.validateHeaders = function validateHeaders(headers) {
if (!headers || Object.prototype.toString.call(headers) !== '[object Object]') {
throw new Error('Headers must be a valid object');
}
}
/**
* Validates GraphQL field selection
*/;
Validators.validateFields = function validateFields(fields) {
if (typeof fields !== 'string' || !fields.trim()) {
throw new Error('Field selection must be a non-empty string');
}
}
/**
* Validates GraphQL arguments
*/;
Validators.validateGraphQLArgs = function validateGraphQLArgs(args) {
if (args && Object.prototype.toString.call(args) !== '[object Object]') {
throw new Error('GraphQL arguments must be an object');
}
}
/**
* Validates constructor arguments
*/;
Validators.validateConstructorArgs = function validateConstructorArgs(baseUrl) {
if (!baseUrl || typeof baseUrl !== 'string') {
throw new Error('Fetchero: "baseUrl" must be a non-empty string.');
}
try {
new URL(baseUrl);
} catch (_unused2) {
throw new Error('Fetchero: "baseUrl" must be a valid URL.');
}
};
return Validators;
}();
/**
* Core HTTP client functionality
*/
var HttpClient = /*#__PURE__*/function () {
function HttpClient(baseUrl, headers, interceptors) {
this.baseUrl = baseUrl;
this.headers = headers;
this.interceptors = interceptors;
}
/**
* Enhanced HTTP request handler with better error handling and performance
*/
var _proto = HttpClient.prototype;
_proto.makeRequest =
/*#__PURE__*/
function () {
var _makeRequest = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config) {
var _this$interceptors, _this$interceptors2, finalConfig, result, _ref, responseData, errors, response, _t, _t2, _t3;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
if (config.url) {
_context.n = 1;
break;
}
throw new Error('Request URL is required');
case 1:
// Apply request interceptor
if (!((_this$interceptors = this.interceptors) != null && _this$interceptors.request)) {
_context.n = 3;
break;
}
_context.n = 2;
return this.interceptors.request(config);
case 2:
_t = _context.v;
_context.n = 4;
break;
case 3:
_t = config;
case 4:
finalConfig = _t;
// Add timeout if not specified
if (!finalConfig.timeout) {
finalConfig.timeout = 30000; // 30 seconds default
}
// Execute request
_context.n = 5;
return axios(finalConfig);
case 5:
result = _context.v;
// Safely extract response data
_ref = result.data || {}, responseData = _ref.data, errors = _ref.errors; // Build response object
response = {
data: responseData != null ? responseData : null
}; // Handle GraphQL errors with improved error processing
if (errors && Array.isArray(errors) && errors.length > 0) {
response.errors = errors.map(function (error) {
return ErrorHandler.compose(error);
});
}
// Apply response interceptor
if (!((_this$interceptors2 = this.interceptors) != null && _this$interceptors2.response)) {
_context.n = 7;
break;
}
_context.n = 6;
return this.interceptors.response(result);
case 6:
_t2 = _context.v;
_context.n = 8;
break;
case 7:
_t2 = response;
case 8:
return _context.a(2, _t2);
case 9:
_context.p = 9;
_t3 = _context.v;
return _context.a(2, this.handleRequestError(_t3));
}
}, _callee, this, [[0, 9]]);
}));
function makeRequest(_x) {
return _makeRequest.apply(this, arguments);
}
return makeRequest;
}()
/**
* Enhanced error handling with better error categorization
*/
;
_proto.handleRequestError = function handleRequestError(err) {
var _error$response$statu, _error$response, _error$response2, _error$response3;
var error = err;
// Determine error status and message
var status = (_error$response$statu = (_error$response = error.response) == null ? void 0 : _error$response.status) != null ? _error$response$statu : error.code === 'ECONNABORTED' ? 408 : 500;
var message;
if ((_error$response2 = error.response) != null && (_error$response2 = _error$response2.data) != null && _error$response2.message) {
message = error.response.data.message;
} else if ((_error$response3 = error.response) != null && (_error$response3 = _error$response3.data) != null && _error$response3.error) {
message = error.response.data.error;
} else if (error.code === 'ECONNABORTED') {
message = 'Request timeout';
} else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
message = 'Network connection failed';
} else {
message = error.message || 'Network request failed';
}
return {
data: null,
errors: [ErrorHandler.makeErrorResponse({
code: status,
message: message
})]
};
};
return HttpClient;
}();
/**
* REST proxy implementation with caching and performance optimizations
*/
var RestProxyFactory = /*#__PURE__*/function () {
function RestProxyFactory(httpClient, baseUrl, headers) {
this.httpClient = httpClient;
this.baseUrl = baseUrl;
this.headers = headers;
}
/**
* Creates REST proxy
*/
var _proto = RestProxyFactory.prototype;
_proto.createProxy = function createProxy(segments, ctx) {
var _this = this;
if (segments === void 0) {
segments = [];
}
if (ctx === void 0) {
ctx = {};
}
var proxyTarget = function proxyTarget() {};
return new Proxy(proxyTarget, {
get: function get(_, prop) {
if (typeof prop !== 'string') return undefined;
// Handle configuration methods
switch (prop) {
case 'base':
return function (newBase) {
Validators.validateUrl(newBase);
return _this.createProxy(segments, _extends({}, ctx, {
base: newBase
}));
};
case 'headers':
return function (newHeaders) {
Validators.validateHeaders(newHeaders);
return _this.createProxy(segments, _extends({}, ctx, {
headers: _extends({}, ctx.headers, newHeaders)
}));
};
}
// Handle HTTP methods
if (_this.isHttpMethod(prop)) {
return /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(options) {
var _ctx$base;
var url;
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
if (options === void 0) {
options = {};
}
url = URLBuilder.build((_ctx$base = ctx.base) != null ? _ctx$base : _this.baseUrl, segments, options.query);
return _context.a(2, _this.httpClient.makeRequest({
url: url,
method: prop.toUpperCase(),
data: options.body,
transformResponse: function transformResponse(response) {
return {
data: JSON.parse(response)
};
},
headers: _extends({}, _this.headers, ctx.headers, options.headers)
}));
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}();
}
// Create new proxy for path segments
return _this.createProxy([].concat(segments, [prop]), ctx);
},
apply: function apply(_, __, args) {
var validArgs = args.filter(function (arg) {
return arg != null;
}).map(String);
return _this.createProxy([].concat(segments, validArgs), ctx);
}
});
}
/**
* Optimized HTTP method validation using Set
*/;
_proto.isHttpMethod = function isHttpMethod(method) {
return RestProxyFactory.HTTP_METHODS.has(method.toLowerCase());
};
return RestProxyFactory;
}();
RestProxyFactory.HTTP_METHODS = /*#__PURE__*/new Set(['get', 'post', 'put', 'patch', 'delete']);
// @ts-nocheck
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
var isValidInitialString = /^(mutation|query)(?:\s+)?{|^(?!mutation|query)\w+(?:\s+)?(?:{|\()/i;
var isEmpty = function isEmpty(obj) {
return Object.keys(obj).length === 0;
};
var inSingleLine = function inSingleLine(query) {
return query.trim().replace(/\n/g, ' ')
// It is necessary to keep two separate replacements
.replace(/\s{2,}/g, ' ');
};
function typeOf(value) {
var type = typeof value;
if (isObject(value)) {
if (value.type) return value.type;
type = typeof value.value;
}
return {
number: 'Int',
string: 'String',
"boolean": 'Boolean'
}[type];
}
function getValue(value, key) {
if (['number', 'string', 'boolean'].includes(typeof value)) return value;
if (isObject(value) && value.value) return value.value;
throw new Error("The value is not in acceptable format for " + key);
}
function processArgsList(argsList) {
var variables = {};
var queryStrings = [];
var argsStrings = argsList.map(function (args, idx) {
var argsString = [];
for (var key in args) {
var value = getValue(args[key], key);
var type = typeOf(args[key]);
var variableName = key + "_" + idx;
if (!type) {
throw new Error("`type` is not defined for `" + key + "` property");
}
variables[variableName] = value;
queryStrings.push("$" + variableName + ": " + type);
argsString.push(key + ": $" + variableName);
}
return argsString.join(', ');
});
return {
variables: variables,
argsStrings: argsStrings,
varString: queryStrings.join(', ')
};
}
function constructString(strings, argsStrings) {
var resultString = strings.map(function (string, position) {
return string + (argsStrings[position] || '');
}).join('');
var firstPartPat = /^(mutation|query)\s+{/;
if (firstPartPat.test(strings[0].trim())) {
return resultString.replace(firstPartPat, '').replace(/}$/, '');
}
return resultString;
}
function buildQuery(strings) {
var initialString = strings[0].trim();
if (!isValidInitialString.test(initialString)) {
throw new Error('The query string is not valid');
}
var isMutation = /^mutation\s+{/.test(initialString);
var queryType = isMutation ? 'mutation' : 'query';
for (var _len = arguments.length, argsList = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
argsList[_key - 1] = arguments[_key];
}
var _processArgsList = processArgsList(argsList),
variables = _processArgsList.variables,
argsStrings = _processArgsList.argsStrings,
varString = _processArgsList.varString;
var queryString = varString ? "my_" + queryType + "(" + varString + ")" : '';
var query = queryType + " " + queryString + " {\n " + constructString(strings, argsStrings) + "\n }";
var result = {
query: inSingleLine(query)
};
if (!isEmpty(variables)) result.variables = variables;
return result;
}
/**
* GraphQL proxy implementation with enhanced error handling
*/
var GraphQLProxyFactory = /*#__PURE__*/function () {
function GraphQLProxyFactory(httpClient, baseUrl, headers) {
this.httpClient = httpClient;
this.baseUrl = baseUrl;
this.headers = headers;
}
/**
* Creates GraphQL proxy
*/
var _proto = GraphQLProxyFactory.prototype;
_proto.createProxy = function createProxy(ctx) {
var _this = this;
return new Proxy({}, {
get: function get(_, operation) {
if (typeof operation !== 'string') return undefined;
var operationType = operation.toLowerCase();
if (!_this.isValidGraphQLOperation(operationType)) {
throw new Error("Invalid GraphQL operation \"" + operation + "\". Valid operations: query, mutation, subscription");
}
try {
return _this.createOperationProxy(operationType, ctx);
} catch (error) {
console.log({
error: error
}, 'abul boom');
return error;
}
}
});
}
/**
* Optimized GraphQL operation validation
*/;
_proto.isValidGraphQLOperation = function isValidGraphQLOperation(operation) {
return GraphQLProxyFactory.GRAPHQL_OPERATIONS.has(operation);
}
/**
* Creates operation-specific proxy
*/;
_proto.createOperationProxy = function createOperationProxy(operation, ctx) {
var _this2 = this;
var proxyTarget = function proxyTarget() {};
return new Proxy(proxyTarget, {
get: function get(_, field) {
if (typeof field !== 'string') return undefined;
return _this2.createQueryBuilder(operation, field, {}, ctx);
}
});
}
/**
* Creates GraphQL query builder with improved caching
*/;
_proto.createQueryBuilder = function createQueryBuilder(operation, field, argsObj, ctx) {
var _this3 = this;
// Memoize operation building for performance
var buildOperation = function buildOperation(selectedFields) {
if (selectedFields === void 0) {
selectedFields = '';
}
return _this3.buildGraphQLOperation(operation, field, argsObj, selectedFields);
};
var built = buildOperation();
var fn = function fn() {};
return new Proxy(fn, {
get: function get(_, prop) {
if (typeof prop !== 'string') return undefined;
switch (prop) {
case 'select':
return function (selectedFields) {
Validators.validateFields(selectedFields);
var rebuilt = buildOperation(selectedFields);
return _this3.executeGraphQLQuery(rebuilt.query, rebuilt.variables, ctx);
};
case 'execute':
return function () {
return _this3.executeGraphQLQuery(built.query, built.variables, ctx);
};
case 'then':
return function (resolve, reject) {
return _this3.executeGraphQLQuery(built.query, built.variables, ctx).then(resolve, reject);
};
case 'base':
return function (newBase) {
Validators.validateUrl(newBase);
return _this3.createQueryBuilder(operation, field, argsObj, _extends({}, ctx, {
base: newBase
}));
};
case 'headers':
return function (newHeaders) {
Validators.validateHeaders(newHeaders);
return _this3.createQueryBuilder(operation, field, argsObj, _extends({}, ctx, {
headers: _extends({}, ctx.headers, newHeaders)
}));
};
default:
throw new Error("Invalid property \"" + prop + "\". Available methods: select(fields), execute(), base(url), headers(obj)");
}
},
apply: function apply(_, __, _ref) {
var argsObj = _ref[0];
Validators.validateGraphQLArgs(argsObj);
return _this3.createQueryBuilder(operation, field, argsObj || {}, ctx);
}
});
}
/**
* Builds GraphQL operation with enhanced error handling and validation
*/;
_proto.buildGraphQLOperation = function buildGraphQLOperation(operation, field, argsObj, selection) {
try {
// Validate inputs
if (!field || typeof field !== 'string') {
throw new Error('Field name must be a non-empty string');
}
var cleanedSelection = selection == null ? void 0 : selection.trim();
var hasArgs = argsObj && Object.keys(argsObj).length > 0;
var select = cleanedSelection ? "{ " + cleanedSelection + " }" : '';
var templateParts = hasArgs ? [operation + " { " + field + " (", ") " + select + " }"] : [operation + " { " + field + " ", " " + select + " }"];
var result = buildQuery(templateParts, argsObj || {});
// Validate the built query
if (!result.query || typeof result.query !== 'string') {
throw new Error('Failed to generate valid GraphQL query');
}
return result;
} catch (error) {
var message = error instanceof Error ? error.message : 'Unknown error';
throw new Error("Failed to build GraphQL " + operation + " for field \"" + field + "\": " + message);
}
}
/**
* Executes GraphQL query with comprehensive error handling
*/;
_proto.executeGraphQLQuery =
/*#__PURE__*/
function () {
var _executeGraphQLQuery = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(query, variables, ctx) {
var _ctx$base;
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
if (!(!query || typeof query !== 'string')) {
_context.n = 1;
break;
}
throw new Error('GraphQL query must be a non-empty string');
case 1:
return _context.a(2, this.httpClient.makeRequest({
url: (_ctx$base = ctx.base) != null ? _ctx$base : this.baseUrl,
method: 'POST',
data: {
query: query,
variables: variables || {}
},
headers: _extends({
'Content-Type': 'application/json'
}, this.headers, ctx.headers)
}));
}
}, _callee, this);
}));
function executeGraphQLQuery(_x, _x2, _x3) {
return _executeGraphQLQuery.apply(this, arguments);
}
return executeGraphQLQuery;
}();
return GraphQLProxyFactory;
}();
GraphQLProxyFactory.GRAPHQL_OPERATIONS = /*#__PURE__*/new Set(['query', 'mutation', 'subscription']);
/**
* Enhanced Fetchero class with separated concerns
*/
var Fetchero = /*#__PURE__*/function () {
function Fetchero(_ref) {
var baseUrl = _ref.baseUrl,
_ref$headers = _ref.headers,
headers = _ref$headers === void 0 ? {} : _ref$headers,
interceptors = _ref.interceptors;
Validators.validateConstructorArgs(baseUrl);
// this.baseUrl = baseUrl;
this.headers = Object.freeze(_extends({}, headers));
// Initialize HTTP client
this.httpClient = new HttpClient(baseUrl, this.headers, interceptors);
// Initialize proxy factories
this.restProxyFactory = new RestProxyFactory(this.httpClient, baseUrl, this.headers);
this.graphqlProxyFactory = new GraphQLProxyFactory(this.httpClient, baseUrl, this.headers);
}
/**
* Returns REST proxy interface
*/
return _createClass(Fetchero, [{
key: "rest",
get: function get() {
if (!this.restProxy) {
this.restProxy = this.restProxyFactory.createProxy();
}
return this.restProxy;
}
/**
* Returns GraphQL proxy interface
*/
}, {
key: "gql",
get: function get() {
if (!this.gqlProxy) {
this.gqlProxy = this.graphqlProxyFactory.createProxy({});
}
return this.gqlProxy;
}
}]);
}();
/**
* Creates a Fetchero instance with both REST and GraphQL interfaces
*/
var createFetchero = function createFetchero(options) {
var instance = new Fetchero(options);
return Object.freeze({
rest: instance.rest,
gql: instance.gql
});
};
/**
* Creates a standalone REST client
*/
var rest = function rest(options) {
return new Fetchero(options).rest;
};
/**
* Creates a standalone GraphQL client
*/
var gql = function gql(options) {
return new Fetchero(options).gql;
};
exports.ErrorHandler = ErrorHandler;
exports.Fetchero = Fetchero;
exports.URLBuilder = URLBuilder;
exports.Validators = Validators;
exports.createFetchero = createFetchero;
exports.gql = gql;
exports.rest = rest;
//# sourceMappingURL=fetchero.cjs.development.js.map