UNPKG

@iamnnort/request

Version:

Request handler for Node.js - Fast - Interactive - Simple

546 lines (522 loc) 20.3 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/builder.ts var _qs = require('qs'); // src/types.ts var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => { HttpMethods2["GET"] = "get"; HttpMethods2["POST"] = "post"; HttpMethods2["PUT"] = "put"; HttpMethods2["DELETE"] = "delete"; return HttpMethods2; })(HttpMethods || {}); var HttpStatuses = /* @__PURE__ */ ((HttpStatuses2) => { HttpStatuses2[HttpStatuses2["CONTINUE"] = 100] = "CONTINUE"; HttpStatuses2[HttpStatuses2["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS"; HttpStatuses2[HttpStatuses2["PROCESSING"] = 102] = "PROCESSING"; HttpStatuses2[HttpStatuses2["EARLYHINTS"] = 103] = "EARLYHINTS"; HttpStatuses2[HttpStatuses2["OK"] = 200] = "OK"; HttpStatuses2[HttpStatuses2["CREATED"] = 201] = "CREATED"; HttpStatuses2[HttpStatuses2["ACCEPTED"] = 202] = "ACCEPTED"; HttpStatuses2[HttpStatuses2["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION"; HttpStatuses2[HttpStatuses2["NO_CONTENT"] = 204] = "NO_CONTENT"; HttpStatuses2[HttpStatuses2["RESET_CONTENT"] = 205] = "RESET_CONTENT"; HttpStatuses2[HttpStatuses2["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT"; HttpStatuses2[HttpStatuses2["AMBIGUOUS"] = 300] = "AMBIGUOUS"; HttpStatuses2[HttpStatuses2["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY"; HttpStatuses2[HttpStatuses2["FOUND"] = 302] = "FOUND"; HttpStatuses2[HttpStatuses2["SEE_OTHER"] = 303] = "SEE_OTHER"; HttpStatuses2[HttpStatuses2["NOT_MODIFIED"] = 304] = "NOT_MODIFIED"; HttpStatuses2[HttpStatuses2["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT"; HttpStatuses2[HttpStatuses2["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT"; HttpStatuses2[HttpStatuses2["BAD_REQUEST"] = 400] = "BAD_REQUEST"; HttpStatuses2[HttpStatuses2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED"; HttpStatuses2[HttpStatuses2["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED"; HttpStatuses2[HttpStatuses2["FORBIDDEN"] = 403] = "FORBIDDEN"; HttpStatuses2[HttpStatuses2["NOT_FOUND"] = 404] = "NOT_FOUND"; HttpStatuses2[HttpStatuses2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED"; HttpStatuses2[HttpStatuses2["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE"; HttpStatuses2[HttpStatuses2["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED"; HttpStatuses2[HttpStatuses2["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT"; HttpStatuses2[HttpStatuses2["CONFLICT"] = 409] = "CONFLICT"; HttpStatuses2[HttpStatuses2["GONE"] = 410] = "GONE"; HttpStatuses2[HttpStatuses2["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED"; HttpStatuses2[HttpStatuses2["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED"; HttpStatuses2[HttpStatuses2["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE"; HttpStatuses2[HttpStatuses2["URI_TOO_LONG"] = 414] = "URI_TOO_LONG"; HttpStatuses2[HttpStatuses2["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE"; HttpStatuses2[HttpStatuses2["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE"; HttpStatuses2[HttpStatuses2["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED"; HttpStatuses2[HttpStatuses2["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT"; HttpStatuses2[HttpStatuses2["MISDIRECTED"] = 421] = "MISDIRECTED"; HttpStatuses2[HttpStatuses2["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY"; HttpStatuses2[HttpStatuses2["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY"; HttpStatuses2[HttpStatuses2["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED"; HttpStatuses2[HttpStatuses2["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS"; HttpStatuses2[HttpStatuses2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR"; HttpStatuses2[HttpStatuses2["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED"; HttpStatuses2[HttpStatuses2["BAD_GATEWAY"] = 502] = "BAD_GATEWAY"; HttpStatuses2[HttpStatuses2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE"; HttpStatuses2[HttpStatuses2["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT"; HttpStatuses2[HttpStatuses2["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED"; return HttpStatuses2; })(HttpStatuses || {}); // src/builder.ts var RequestBuilder = class { constructor(params) { this.baseConfig = params.baseConfig; this.requestConfig = params.requestConfig; this.config = { timeout: params.requestConfig.timeout || params.baseConfig.timeout, responseType: params.requestConfig.responseType || params.baseConfig.responseType, headers: { Accept: "application/json", "Content-Type": "application/json", ...params.baseConfig.headers, ...params.requestConfig.headers } }; } makeContentType() { if (this.requestConfig.multipart) { this.config = { ...this.config, headers: { ...this.config.headers, "Content-Type": "multipart/form-data" } }; return this; } if (this.requestConfig.urlencoded) { this.config = { ...this.config, headers: { ...this.config.headers, "Content-Type": "application/x-www-form-urlencoded" } }; return this; } if (this.requestConfig.xml) { this.config = { ...this.config, headers: { ...this.config.headers, "Content-Type": "text/xml" } }; return this; } return this; } makeAuth() { const auth = this.requestConfig.auth || this.baseConfig.auth; if (auth) { this.config = { ...this.config, auth }; return this; } const bearerToken = this.requestConfig.bearerToken || this.baseConfig.bearerToken; if (bearerToken) { this.config = { ...this.config, headers: { ...this.config.headers, Authorization: `Bearer ${bearerToken}` } }; return this; } const apiKey = this.requestConfig.apiKey || this.baseConfig.apiKey; if (apiKey) { this.config = { ...this.config, headers: { ...this.config.headers, "x-api-key": apiKey } }; return this; } return this; } makeUrl() { const baseUrlMap = this.requestConfig.baseUrlMap || this.baseConfig.baseUrlMap; const baseUrlName = this.requestConfig.baseUrlName || this.baseConfig.baseUrlName; const urlParts = [ baseUrlMap && baseUrlName ? baseUrlMap[baseUrlName] : this.baseConfig.baseUrl, this.baseConfig.url, ...this.baseConfig.urlParts || [], this.requestConfig.baseUrl, this.requestConfig.url, ...this.requestConfig.urlParts || [] ].map((urlPart) => _optionalChain([urlPart, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])); const isSecureProtocol = urlParts.some((urlPart) => _optionalChain([urlPart, 'optionalAccess', _4 => _4.includes, 'call', _5 => _5("https")])); const protocol = isSecureProtocol ? "https" : "http"; const actualUrlParts = urlParts.filter((urlPart) => urlPart).map((urlPart) => { return _optionalChain([urlPart, 'optionalAccess', _6 => _6.replace, 'call', _7 => _7(/^(https?:\/\/|\/)?(.*?)(\/?)$/, "$2")]); }); const url = `${protocol}://${actualUrlParts.join("/")}`; this.config = { ...this.config, url }; return this; } makeMethod() { this.config = { ...this.config, method: this.requestConfig.method }; return this; } makeData() { if (this.requestConfig.method === "get" /* GET */) { return this; } if (this.requestConfig.urlencoded) { this.config = { ...this.config, data: _qs.stringify.call(void 0, this.requestConfig.data) }; return this; } this.config = { ...this.config, data: this.requestConfig.data }; return this; } makeParams() { this.config = { ...this.config, params: this.requestConfig.params }; return this; } makeSerializer() { this.config = { ...this.config, paramsSerializer: (params) => { return _qs.stringify.call(void 0, params, { arrayFormat: _optionalChain([this, 'access', _8 => _8.baseConfig, 'access', _9 => _9.serializer, 'optionalAccess', _10 => _10.array]) || "brackets", skipNulls: true }); } }; return this; } build() { return this.config; } }; // src/data-source.ts var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios); // src/logger/builder.ts var MessageBuilder = class { constructor(config) { this.printQueue = []; this.config = config; } setRequest(request) { this.request = request; return this; } setResponse(response) { this.response = response; return this; } setError(error) { this.error = error; return this; } makeType(type) { this.printQueue.push(`[${type}]`); return this; } makeUrl() { const url = _optionalChain([this, 'access', _11 => _11.request, 'optionalAccess', _12 => _12.url]) || _optionalChain([this, 'access', _13 => _13.response, 'optionalAccess', _14 => _14.config, 'optionalAccess', _15 => _15.url]) || _optionalChain([this, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.response, 'optionalAccess', _18 => _18.config, 'access', _19 => _19.url]); const params = _optionalChain([this, 'access', _20 => _20.request, 'optionalAccess', _21 => _21.params]) || _optionalChain([this, 'access', _22 => _22.response, 'optionalAccess', _23 => _23.config, 'optionalAccess', _24 => _24.params]) || _optionalChain([this, 'access', _25 => _25.error, 'optionalAccess', _26 => _26.response, 'optionalAccess', _27 => _27.config, 'access', _28 => _28.params]); if (url) { if (params) { delete params["0"]; this.printQueue.push( [ url, _qs.stringify.call(void 0, params, { arrayFormat: _optionalChain([this, 'access', _29 => _29.config, 'access', _30 => _30.serializer, 'optionalAccess', _31 => _31.array]) || "brackets", skipNulls: true }) ].filter((_) => _).join("?") ); } else { this.printQueue.push(url); } } return this; } makeMethodText() { const method = _optionalChain([this, 'access', _32 => _32.request, 'optionalAccess', _33 => _33.method]) || _optionalChain([this, 'access', _34 => _34.response, 'optionalAccess', _35 => _35.config, 'optionalAccess', _36 => _36.method]) || _optionalChain([this, 'access', _37 => _37.error, 'optionalAccess', _38 => _38.response, 'optionalAccess', _39 => _39.config, 'access', _40 => _40.method]); if (method) { this.printQueue.push(method.toUpperCase()); } return this; } makeRequestData() { const data = _optionalChain([this, 'access', _41 => _41.request, 'optionalAccess', _42 => _42.data]) || _optionalChain([this, 'access', _43 => _43.response, 'optionalAccess', _44 => _44.config, 'optionalAccess', _45 => _45.data]) || _optionalChain([this, 'access', _46 => _46.error, 'optionalAccess', _47 => _47.response, 'optionalAccess', _48 => _48.config, 'access', _49 => _49.data]); if (data) { if (typeof data === "string") { this.printQueue.push(data); return this; } if (Object.keys(data).length) { this.printQueue.push(JSON.stringify(data)); return this; } } return this; } makeResponseDataText() { const data = _optionalChain([this, 'access', _50 => _50.response, 'optionalAccess', _51 => _51.data]) || _optionalChain([this, 'access', _52 => _52.error, 'optionalAccess', _53 => _53.response, 'optionalAccess', _54 => _54.data]); if (data) { if (typeof data === "string") { this.printQueue.push(data); return this; } if (Object.keys(data).length) { this.printQueue.push(JSON.stringify(data)); return this; } } return this; } makeStatusText() { const status = _optionalChain([this, 'access', _55 => _55.response, 'optionalAccess', _56 => _56.status]) || _optionalChain([this, 'access', _57 => _57.error, 'optionalAccess', _58 => _58.response, 'optionalAccess', _59 => _59.status]); if (status) { this.printQueue.push(`${status}`); const statusText = _optionalChain([this, 'access', _60 => _60.response, 'optionalAccess', _61 => _61.statusText]) || _optionalChain([this, 'access', _62 => _62.error, 'optionalAccess', _63 => _63.response, 'optionalAccess', _64 => _64.statusText]); if (statusText) { this.printQueue.push(statusText); } } return this; } build() { return this.printQueue.join(" "); } makeMethod() { const method = _optionalChain([this, 'access', _65 => _65.request, 'optionalAccess', _66 => _66.method]) || _optionalChain([this, 'access', _67 => _67.response, 'optionalAccess', _68 => _68.config, 'optionalAccess', _69 => _69.method]) || _optionalChain([this, 'access', _70 => _70.error, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.config, 'access', _73 => _73.method]); if (!method) { return "get" /* GET */; } return method.toLowerCase(); } makeResponseData() { const data = _optionalChain([this, 'access', _74 => _74.response, 'optionalAccess', _75 => _75.data]) || _optionalChain([this, 'access', _76 => _76.error, 'optionalAccess', _77 => _77.response, 'optionalAccess', _78 => _78.data]); if (!data) { return ""; } if (typeof data === "string") { return data; } return JSON.stringify(data); } makeStatus() { const status = _optionalChain([this, 'access', _79 => _79.response, 'optionalAccess', _80 => _80.status]) || _optionalChain([this, 'access', _81 => _81.error, 'optionalAccess', _82 => _82.response, 'optionalAccess', _83 => _83.status]); if (!status) { return 500 /* INTERNAL_SERVER_ERROR */; } return status; } makeResponse() { return { success: this.error === void 0, status: this.makeStatus(), method: this.makeMethod(), data: this.makeResponseData() }; } }; // src/logger/service.ts var LoggerService = class { constructor(config) { this.config = config; } log(message, context) { const ctx = context || this.config.name || ""; if (ctx) { return console.log(`[${ctx}] ${message}`); } return console.log(message); } logRequest(request) { const loggerMessageBuilder = new MessageBuilder(this.config); const message = loggerMessageBuilder.setRequest(request).makeType("Request").makeMethodText().makeUrl().makeRequestData().build(); return this.log(message); } logResponse(response) { const loggerMessageBuilder = new MessageBuilder(this.config); const message = loggerMessageBuilder.setResponse(response).makeType("Response").makeMethodText().makeUrl().makeRequestData().makeStatusText().makeResponseDataText().build(); return this.log(message); } logRequestError(error) { const loggerMessageBuilder = new MessageBuilder(this.config); const message = loggerMessageBuilder.setError(error).makeType("Error").makeMethodText().makeUrl().makeRequestData().makeStatusText().makeResponseDataText().build(); return this.log(message); } makeResponse(response) { const loggerMessageBuilder = new MessageBuilder(this.config); const responseData = loggerMessageBuilder.setResponse(response).makeResponse(); return responseData; } makeErrorResponse(error) { const loggerMessageBuilder = new MessageBuilder(this.config); const errorResponseData = loggerMessageBuilder.setError(error).makeResponse(); return errorResponseData; } }; // src/data-source.ts var RequestDataSource = class { constructor(baseRequestConfig) { this.baseRequestConfig = baseRequestConfig; } common(requestConfig, responseConfig = {}) { const loggerService = new LoggerService(this.baseRequestConfig); const requestBuilder = new RequestBuilder({ baseConfig: this.baseRequestConfig, requestConfig }); const request = requestBuilder.makeContentType().makeAuth().makeUrl().makeMethod().makeParams().makeData().makeSerializer().build(); if (this.baseRequestConfig.logger) { loggerService.logRequest(request); } return _axios2.default.request(request).then((response) => { if (this.baseRequestConfig.logger) { loggerService.logResponse(response); } if (responseConfig.raw) { return loggerService.makeResponse(response); } return response.data; }).catch((error) => { if (this.baseRequestConfig.debug) { console.log("Error:", error); } if (this.baseRequestConfig.logger) { loggerService.logRequestError(error); } if (responseConfig.raw) { return loggerService.makeErrorResponse(error); } throw _optionalChain([error, 'access', _84 => _84.response, 'optionalAccess', _85 => _85.data]) || error.response || new Error(error.message); }); } async *bulkCommon(requestConfig, responseConfig = {}) { const { params } = requestConfig; const { bulkCallback } = responseConfig; const { page, pageSize, bulkSize, ...searchDto } = params || {}; const paginationDto = { page: page || 1, pageSize: pageSize || 30 }; const maxPage = bulkSize ? paginationDto.page - 1 + bulkSize : null; let pagination = { total: 0, currentPage: 0, lastPage: 0, from: 0, to: 0, pageSize: 0 }; do { const response = await this.common({ ...requestConfig, params: { ...paginationDto, ...searchDto } }); pagination = response.pagination; if (!_optionalChain([response, 'access', _86 => _86.data, 'optionalAccess', _87 => _87.length])) { return; } yield response.data; paginationDto.page += 1; } while (pagination.currentPage !== pagination.lastPage && pagination.currentPage !== maxPage); if (pagination.currentPage !== pagination.lastPage) { if (bulkCallback) { await bulkCallback(paginationDto.page); } } } search(config = {}) { return this.common({ ...config, method: "get" /* GET */ }); } bulkSearch(config = {}) { return this.bulkCommon({ ...config, method: "get" /* GET */ }); } get(id, config = {}) { return this.common({ ...config, method: "get" /* GET */, url: id }); } create(config) { return this.common({ ...config, method: "post" /* POST */ }); } bulkCreate(config) { return this.common({ ...config, method: "post" /* POST */, url: "/bulk", data: { bulk: config.data } }); } update(id, config) { return this.common({ ...config, method: "put" /* PUT */, url: id }); } bulkUpdate(config) { return this.common({ ...config, method: "put" /* PUT */, url: "/bulk", data: { bulk: config.data } }); } remove(id, config = {}) { return this.common({ ...config, method: "delete" /* DELETE */, url: id }); } }; // src/helper.ts var RequestHelper = class { static sleep(seconds) { return new Promise((resolve) => { setTimeout(resolve, seconds * 1e3); }); } }; exports.HttpMethods = HttpMethods; exports.HttpStatuses = HttpStatuses; exports.RequestBuilder = RequestBuilder; exports.RequestDataSource = RequestDataSource; exports.RequestHelper = RequestHelper; //# sourceMappingURL=index.js.map