@autofleet/network 1.8.18 → 1.8.20-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`),l=require(`node:module`),u=require(`axios`);u=s(u);let d=require(`axios-retry`);d=s(d);let f=require(`@autofleet/logger`);f=s(f);let p=require(`deepmerge`);p=s(p);let m=require(`@autofleet/axios-cache-adapter`);m=s(m);let h=require(`agentkeepalive`);const{setup:g}=m.default,_=d.default,v=(0,l.createRequire)(require(`url`).pathToFileURL(__filename).href);let y;const b=(...e)=>(y??=v(`qs`).stringify,y(...e)),x=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],S={arrayFormat:`brackets`},C={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":c.env.AF_SERVICE_NAME||null},paramsSerializer:e=>b(e,S),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},w=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,T=Number.parseInt(c.env.FREE_SOCKET_TIMEOUT||``,10)||5e3;var E=class{#e;constructor(e={}){this.#e=e.logger??(0,f.default)(),this.settings=(0,p.default)(C,e),this.settings.keepAlive&&(this.settings.httpAgent=new h.HttpAgent({freeSocketTimeout:T}),this.settings.httpsAgent=new h.HttpsAgent({freeSocketTimeout:T}),delete this.settings.keepAlive),this.#r(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?g(this.settings):u.default.create(this.settings),this.#t(e),this.#i(),this.#n()}#t(e){_(this.axios,{retries:0,retryDelay:d.default.exponentialDelay,...e})}#n(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${w(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${w(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?w(t):``}`,{status:e.status,data:e.response?.data}),e})}#r(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;e.serviceUrl?e.baseURL=e.serviceUrl:e.serviceName&&(e.baseURL=`http://${c.env[`${e.serviceName}_SERVICE_HOST`]}`)}#i(){x.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};module.exports=E;
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`),l=require(`node:module`),u=require(`axios`);u=s(u);let d=require(`axios-retry`);d=s(d);let f=require(`@autofleet/logger`);f=s(f);let p=require(`deepmerge`);p=s(p);let m=require(`@autofleet/axios-cache-adapter`);m=s(m);let h=require(`agentkeepalive`);const{setup:g}=m.default,_=d.default,v=(0,l.createRequire)(require(`url`).pathToFileURL(__filename).href);let y;const b=(...e)=>(y??=v(`qs`).stringify,y(...e)),x=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],S={arrayFormat:`brackets`},C={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":c.env.AF_SERVICE_NAME||null},paramsSerializer:e=>b(e,S),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},w=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,T=Number.parseInt(c.env.FREE_SOCKET_TIMEOUT||``,10)||5e3;var E=class{#e;constructor(e={}){this.#e=e.logger??(0,f.default)(),this.settings=(0,p.default)(C,e),this.settings.keepAlive?(this.settings.httpAgent=new h.HttpAgent({freeSocketTimeout:T}),this.settings.httpsAgent=new h.HttpsAgent({freeSocketTimeout:T}),delete this.settings.keepAlive):this.settings.keepAlive===!1&&(this.settings.httpAgent=new h.HttpAgent({keepAlive:!1}),this.settings.httpsAgent=new h.HttpsAgent({keepAlive:!1}),delete this.settings.keepAlive),this.#r(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?g(this.settings):u.default.create(this.settings),this.#t(e),this.#i(),this.#n()}#t(e){_(this.axios,{retries:0,retryDelay:d.default.exponentialDelay,...e})}#n(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${w(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${w(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?w(t):``}`,{status:e.status,data:e.response?.data}),e})}#r(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;e.serviceUrl?e.baseURL=e.serviceUrl:e.serviceName&&(e.baseURL=`http://${c.env[`${e.serviceName}_SERVICE_HOST`]}`)}#i(){x.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};module.exports=E;
2
2
  //# sourceMappingURL=index.cjs.map
package/lib/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["axiosCacheAdapter","axiosRetry","qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","env","#logger","HttpAgent","HttpsAgent","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"],"mappings":"svBAsBA,KAAM,CAAE,SAAUA,EAAAA,QACZ,EAA2BC,EAAAA,QAE3B,GAAA,EAAA,EAAA,eAAA,QAAA,MAAA,CAAA,cAAA,WAAA,CAAA,KAA4C,CAElD,IAAIC,EACJ,MAAM,GAAyB,GAAG,KAChC,IAAgB,EAAY,KAAK,CAAC,UAC3B,EAAa,GAAG,EAAK,EAGxB,EAAc,CAClB,MACA,OACA,SACA,OACA,MACA,QACA,UACD,CAEKC,EAAmE,CAAE,YAAa,WAAY,CAU9FC,EAAmC,CACvC,QAAS,IACT,QAAS,CACP,YAAa,SACb,uBAAwBC,EAAAA,IAAI,iBAAmB,KAChD,CACD,iBAAkB,GAAU,EAAsB,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,CAC7G,IAAMF,EAAqB,EAAE,CAEzB,EAAoB,GACpB,EAAO,EACX,KAAO,IAAsB,IAAc,IAAM,EAAO,IAAY,CAClE,GAAM,CAAE,QAAS,MAAM,KAAK,KAAoC,EAAK,CACnE,GAAG,EACH,OACD,CAAC,CACI,CAAE,OAAM,SAAU,EACxB,GAAQ,EACR,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAC/C,EAAoB,EAAc,OAAS,EAG7C,OAAO"}
1
+ {"version":3,"file":"index.cjs","names":["axiosCacheAdapter","axiosRetry","qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","env","#logger","HttpAgent","HttpsAgent","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n } else if (this.settings.keepAlive === false) {\n this.settings.httpAgent = new HttpAgent({ keepAlive: false });\n this.settings.httpsAgent = new HttpsAgent({ keepAlive: false });\n delete this.settings.keepAlive;\n }\n\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"],"mappings":"svBAsBA,KAAM,CAAE,SAAUA,EAAAA,QACZ,EAA2BC,EAAAA,QAE3B,GAAA,EAAA,EAAA,eAAA,QAAA,MAAA,CAAA,cAAA,WAAA,CAAA,KAA4C,CAElD,IAAIC,EACJ,MAAM,GAAyB,GAAG,KAChC,IAAgB,EAAY,KAAK,CAAC,UAC3B,EAAa,GAAG,EAAK,EAGxB,EAAc,CAClB,MACA,OACA,SACA,OACA,MACA,QACA,UACD,CAEKC,EAAmE,CAAE,YAAa,WAAY,CAU9FC,EAAmC,CACvC,QAAS,IACT,QAAS,CACP,YAAa,SACb,uBAAwBC,EAAAA,IAAI,iBAAmB,KAChD,CACD,iBAAkB,GAAU,EAAsB,EAAQ,EAAmB,CAC7E,cAAe,CACb,mBAAoB,GACrB,CACD,UAAW,GACZ,CAEK,EAAuB,GAAwC,KAAK,EAAQ,QAAU,IAAI,aAAa,CAAC,IAAI,EAAQ,SAAW,qBAAqB,EAAQ,KAAO,iBAWnK,EAAsB,OAAO,SAASA,EAAAA,IAAI,qBAAuB,GAAI,GAAG,EAAI,IAElF,IAAqB,EAArB,KAA6B,CAC3B,GAYA,YAAY,EAA4B,EAAE,CAAE,CAC1C,MAAA,EAAe,EAAS,SAAA,EAAA,EAAA,UAAkB,CAC1C,KAAK,UAAA,EAAA,EAAA,SAAiB,EAAiB,EAAS,CAC5C,KAAK,SAAS,WAChB,KAAK,SAAS,UAAY,IAAIE,EAAAA,UAAU,CAAE,kBAAmB,EAAqB,CAAC,CACnF,KAAK,SAAS,WAAa,IAAIC,EAAAA,WAAW,CA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module";import{env as t}from"node:process";import n from"axios";import r from"axios-retry";import i from"@autofleet/logger";import a from"deepmerge";import o from"@autofleet/axios-cache-adapter";import{HttpAgent as s,HttpsAgent as c}from"agentkeepalive";const{setup:l}=o,u=r,d=e(import.meta.url);let f;const p=(...e)=>(f??=d(`qs`).stringify,f(...e)),m=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],h={arrayFormat:`brackets`},g={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":t.AF_SERVICE_NAME||null},paramsSerializer:e=>p(e,h),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},_=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,v=Number.parseInt(t.FREE_SOCKET_TIMEOUT||``,10)||5e3;var y=class{#e;constructor(e={}){this.#e=e.logger??i(),this.settings=a(g,e),this.settings.keepAlive&&(this.settings.httpAgent=new s({freeSocketTimeout:v}),this.settings.httpsAgent=new c({freeSocketTimeout:v}),delete this.settings.keepAlive),this.#r(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?l(this.settings):n.create(this.settings),this.#t(e),this.#i(),this.#n()}#t(e){u(this.axios,{retries:0,retryDelay:r.exponentialDelay,...e})}#n(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${_(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${_(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?_(t):``}`,{status:e.status,data:e.response?.data}),e})}#r(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;e.serviceUrl?e.baseURL=e.serviceUrl:e.serviceName&&(e.baseURL=`http://${t[`${e.serviceName}_SERVICE_HOST`]}`)}#i(){m.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};export{y as default};
1
+ import{createRequire as e}from"node:module";import{env as t}from"node:process";import n from"axios";import r from"axios-retry";import i from"@autofleet/logger";import a from"deepmerge";import o from"@autofleet/axios-cache-adapter";import{HttpAgent as s,HttpsAgent as c}from"agentkeepalive";const{setup:l}=o,u=r,d=e(import.meta.url);let f;const p=(...e)=>(f??=d(`qs`).stringify,f(...e)),m=[`get`,`post`,`delete`,`head`,`put`,`patch`,`options`],h={arrayFormat:`brackets`},g={timeout:1e4,headers:{"X-AF-AUTH":`ANYONE`,"X-IAF-ORIGIN-SERVICE":t.AF_SERVICE_NAME||null},paramsSerializer:e=>p(e,h),"axios-retry":{shouldResetTimeout:!0},keepAlive:!0},_=e=>`[${(e.method||``).toUpperCase()}] ${e.baseURL??`unknown-base-url`}${e.url??`/unknown-url`}`,v=Number.parseInt(t.FREE_SOCKET_TIMEOUT||``,10)||5e3;var y=class{#e;constructor(e={}){this.#e=e.logger??i(),this.settings=a(g,e),this.settings.keepAlive?(this.settings.httpAgent=new s({freeSocketTimeout:v}),this.settings.httpsAgent=new c({freeSocketTimeout:v}),delete this.settings.keepAlive):this.settings.keepAlive===!1&&(this.settings.httpAgent=new s({keepAlive:!1}),this.settings.httpsAgent=new c({keepAlive:!1}),delete this.settings.keepAlive),this.#r(),e.cache&&(this.settings.cache={maxAge:900*1e3,exclude:{query:!1},...e.cache}),this.axios=e.cache?l(this.settings):n.create(this.settings),this.#t(e),this.#i(),this.#n()}#t(e){u(this.axios,{retries:0,retryDelay:r.exponentialDelay,...e})}#n(){this.axios.interceptors.request.use(e=>(this.#e.info(`Start Request: ${_(e)}`),e)),this.axios.interceptors.response.use(e=>(this.#e.info(`Finish Request: ${_(e.config)}`),e),e=>{if(e.request?._currentRequest?.reusedSocket&&[`ECONNRESET`,`EPIPE`].includes(e.code))return this.#e.warn(`${e.code} issue, will retry`,{req:e.request._currentRequest._currentUrl}),this.axios.request(e.config);let t=e.config?.baseURL?e.config:e.request;throw this.#e.error(`Finish Request with error ${t?_(t):``}`,{status:e.status,data:e.response?.data}),e})}#r(){if(!this.settings.serviceUrl&&!this.settings.serviceName)throw Error(`At least one of the settings Missing serviceUrl or serviceName`);let{settings:e}=this;e.serviceUrl?e.baseURL=e.serviceUrl:e.serviceName&&(e.baseURL=`http://${t[`${e.serviceName}_SERVICE_HOST`]}`)}#i(){m.forEach(e=>{this[e]=(...t)=>this.axios[e](...t)})}async getAllPages(e,t={}){let n=[],r=null,i=null,a={params:{page:1},...t};for(a.params.page||=1;(a.params.page===1||i===r)&&i!==0;){let{data:t}=await this.get(e,a);i=t.length,a.params.page===1&&(r=t.length),a.params.page+=1,Array.prototype.push.apply(n,t)}return n}async getAllPagesFromQueryEndpoint(e,t={},n=100){let r=[],i=!0,a=1;for(;i&&(n===-1||a<n);){let{data:n}=await this.post(e,{...t,page:a}),{rows:o,count:s}=n;a+=1,Array.prototype.push.apply(r,o),i=r.length<s}return r}};export{y as default};
2
2
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","#logger","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n }\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"],"mappings":"kSAsBA,KAAM,CAAE,SAAU,EACZ,EAA2B,EAE3B,EAAc,EAAc,OAAO,KAAK,IAAI,CAElD,IAAIA,EACJ,MAAM,GAAyB,GAAG,KAChC,IAAgB,EAAY,KAAK,CAAC,UAC3B,EAAa,GAAG,EAAK,EAGxB,EAAc,CAClB,MACA,OACA,SACA,OACA,MACA,QACA,UACD,CAEKC,EAAmE,CAAE,YAAa,WAAY,CAU9FC,EAAmC,CACvC,QAAS,IACT,QAAS,CACP,YAAa,SACb,uBAAwB,EAAI,iBAAmB,KAChD,CACD,iBAAkB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,KAAO,IAAsB,IAAc,IAAM,EAAO,IAAY,CAClE,GAAM,CAAE,QAAS,MAAM,KAAK,KAAoC,EAAK,CACnE,GAAG,EACH,OACD,CAAC,CACI,CAAE,OAAM,SAAU,EACxB,GAAQ,EACR,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAC/C,EAAoB,EAAc,OAAS,EAG7C,OAAO"}
1
+ {"version":3,"file":"index.js","names":["qsStringify: typeof stringify | undefined","qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]>","defaultSettings: NetworkSettings","#logger","#createBaseUrl","#addRetry","#buildClassHttpMethods","#addLogs","currentResult: T[]","resultsInFirstPage: number | null","lastResultsSize: number | null"],"sources":["../src/index.ts"],"sourcesContent":["import { env } from 'node:process';\nimport { createRequire } from 'node:module';\nimport axios, { type CreateAxiosDefaults, type AxiosRequestConfig, type AxiosInstance, type AxiosResponse, type AxiosRequestHeaders } from 'axios';\nimport axiosRetry, { type IAxiosRetryConfigExtended, type IAxiosRetryConfig, type IAxiosRetryReturn } from 'axios-retry';\nimport Logger, { type LoggerInstanceManager } from '@autofleet/logger';\nimport merge from 'deepmerge';\nimport axiosCacheAdapter from '@autofleet/axios-cache-adapter';\nimport { HttpAgent, HttpsAgent } from 'agentkeepalive';\nimport type { stringify } from 'qs';\nimport type { IAxiosCacheAdapterOptions } from '@autofleet/axios-cache-adapter';\n\ndeclare module 'axios' {\n interface AxiosRequestConfig {\n /** configure how the cached requests will be handled, where they will be stored, etc. */\n cache?: IAxiosCacheAdapterOptions;\n /** force cache invalidation */\n clearCacheEntry?: boolean;\n 'axios-retry'?: IAxiosRetryConfigExtended;\n }\n}\n\n// Due to issue with multiple `axios` versions in monorepo, we need to explicitly override the types to use v0\nconst { setup } = axiosCacheAdapter as { setup: (options: AxiosRequestConfig) => AxiosInstance; };\nconst correctlyTypedAxiosRetry = axiosRetry as unknown as (axiosInstance: AxiosInstance, axiosRetryConfig?: IAxiosRetryConfig) => IAxiosRetryReturn;\n\nconst safeRequire = createRequire(import.meta.url);\n\nlet qsStringify: typeof stringify | undefined;\nconst lazilyLoadQsStringify = (...args: Parameters<typeof stringify>) => {\n qsStringify ??= safeRequire('qs').stringify;\n return qsStringify!(...args);\n};\n\nconst HTTPMethods = [\n 'get',\n 'post',\n 'delete',\n 'head',\n 'put',\n 'patch',\n 'options',\n] as const;\n\nconst qsStringifyOptions: NonNullable<Parameters<typeof stringify>[1]> = { arrayFormat: 'brackets' };\n\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n serviceName?: string;\n serviceUrl?: string;\n keepAlive?: boolean;\n logger?: LoggerInstanceManager;\n timeout?: number;\n}\n\nconst defaultSettings: NetworkSettings = {\n timeout: 10_000,\n headers: {\n 'X-AF-AUTH': 'ANYONE',\n 'X-IAF-ORIGIN-SERVICE': env.AF_SERVICE_NAME || null as unknown as string,\n },\n paramsSerializer: params => lazilyLoadQsStringify(params, qsStringifyOptions),\n 'axios-retry': {\n shouldResetTimeout: true,\n },\n keepAlive: true,\n};\n\nconst createRequestString = (request: AxiosRequestConfig): string => `[${(request.method || '').toUpperCase()}] ${request.baseURL ?? 'unknown-base-url'}${request.url ?? '/unknown-url'}`;\n\n/*\n The default free socket keepalive timeout, in milliseconds.\n Setting to 5000 (5 seconds) as default because out grace period is 10 seconds\n and we want to make sure we don't have any socket issues.\n See https://www.npmjs.com/package/agentkeepalive\n\n There is also autoscaling reason for that, if we don't timeout at some point,\n new pods that were auto scaled will not be used.\n*/\nconst FREE_SOCKET_TIMEOUT = Number.parseInt(env.FREE_SOCKET_TIMEOUT || '', 10) || 5_000;\n\nexport default class Network {\n readonly #logger: LoggerInstanceManager;\n private readonly settings: NetworkSettings;\n private readonly axios: AxiosInstance;\n\n public get!: AxiosInstance['get'];\n public post!: AxiosInstance['post'];\n public delete!: AxiosInstance['delete'];\n public head!: AxiosInstance['head'];\n public put!: AxiosInstance['put'];\n public patch!: AxiosInstance['patch'];\n public options!: AxiosInstance['options'];\n\n constructor(settings: NetworkSettings = {}) {\n this.#logger = settings.logger ?? Logger();\n this.settings = merge(defaultSettings, settings);\n if (this.settings.keepAlive) {\n this.settings.httpAgent = new HttpAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n this.settings.httpsAgent = new HttpsAgent({ freeSocketTimeout: FREE_SOCKET_TIMEOUT });\n delete this.settings.keepAlive;\n } else if (this.settings.keepAlive === false) {\n this.settings.httpAgent = new HttpAgent({ keepAlive: false });\n this.settings.httpsAgent = new HttpsAgent({ keepAlive: false });\n delete this.settings.keepAlive;\n }\n\n this.#createBaseUrl();\n\n if (settings.cache) {\n this.settings.cache = {\n maxAge: 15 * 60 * 1000,\n // Store responses from requests with query parameters in cache\n exclude: { query: false },\n ...settings.cache,\n };\n }\n\n this.axios = settings.cache ? setup(this.settings as NetworkSettings & { headers: AxiosRequestHeaders; }) : axios.create(this.settings);\n this.#addRetry(settings);\n this.#buildClassHttpMethods();\n this.#addLogs();\n }\n\n #addRetry(settings: NetworkSettings): void {\n correctlyTypedAxiosRetry(this.axios, {\n retries: 0,\n retryDelay: axiosRetry.exponentialDelay,\n ...settings,\n });\n }\n\n #addLogs(): void {\n this.axios.interceptors.request.use((request) => {\n this.#logger.info(`Start Request: ${createRequestString(request)}`);\n return request;\n });\n\n this.axios.interceptors.response.use((response) => {\n this.#logger.info(`Finish Request: ${createRequestString(response.config)}`);\n return response;\n }, (error) => {\n if (error.request?._currentRequest?.reusedSocket && ['ECONNRESET', 'EPIPE'].includes(error.code)) {\n // See https://www.npmjs.com/package/agentkeepalive\n // Support req.reusedSocket\n // https://code-examples.net/en/q/28a8069\n this.#logger.warn(`${error.code} issue, will retry`, {\n req: error.request._currentRequest._currentUrl,\n // method: error.request._currentRequest._options.method,\n });\n return this.axios.request(error.config);\n }\n const request = error.config?.baseURL ? error.config : error.request;\n this.#logger.error(`Finish Request with error ${request ? createRequestString(request) : ''}`, {\n status: error.status,\n data: error.response?.data,\n });\n throw error;\n });\n }\n\n #createBaseUrl(): void {\n if (!this.settings.serviceUrl && !this.settings.serviceName) {\n throw new Error('At least one of the settings Missing serviceUrl or serviceName');\n }\n\n const { settings } = this;\n if (settings.serviceUrl) {\n settings.baseURL = settings.serviceUrl;\n } else if (settings.serviceName) {\n const envServiceHostName = `${settings.serviceName}_SERVICE_HOST`;\n settings.baseURL = `http://${env[envServiceHostName]}`;\n }\n }\n\n /**\n * Build class methods that wrap axios methods\n */\n #buildClassHttpMethods(): void {\n HTTPMethods.forEach((method) => {\n this[method] = <T = any, R = AxiosResponse<T>>(\n ...args: Parameters<AxiosInstance[typeof method]>\n ): Promise<R> => this.axios[method](...args as [url: string, leaveUsAlone?: AxiosRequestConfig<unknown>]);\n });\n }\n\n /**\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPages<T>(url: string, options: object = {}): Promise<T[]> {\n const currentResult: T[] = [];\n let resultsInFirstPage: number | null = null;\n let lastResultsSize: number | null = null;\n\n const localOptions = { params: { page: 1 }, ...options };\n // Make sure even if `options` had `params` we initialize `page` to 1.\n localOptions.params.page ||= 1;\n while ((localOptions.params.page === 1 || lastResultsSize === resultsInFirstPage) && lastResultsSize !== 0) {\n const { data } = await this.get<T[]>(url, localOptions);\n lastResultsSize = data.length;\n if (localOptions.params.page === 1) {\n resultsInFirstPage = data.length;\n }\n\n localOptions.params.page += 1;\n Array.prototype.push.apply(currentResult, data);\n }\n\n return currentResult;\n }\n\n /**\n * Fetches all pages from a paginated API endpoint until all results are retrieved\n * or an optional page limit is reached.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional options to include in the request payload.\n * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results.\n */\n public async getAllPagesFromQueryEndpoint<T>(url: string, options: object = {}, pageLimit = 100): Promise<T[]> {\n const currentResult: T[] = [];\n\n let moreResultsToLoad = true;\n let page = 1;\n while (moreResultsToLoad && (pageLimit === -1 || page < pageLimit)) {\n const { data } = await this.post<{ rows: T[]; count: number; }>(url, {\n ...options,\n page,\n });\n const { rows, count } = data;\n page += 1;\n Array.prototype.push.apply(currentResult, rows);\n moreResultsToLoad = currentResult.length < count;\n }\n\n return currentResult;\n }\n};\n"],"mappings":"kSAsBA,KAAM,CAAE,SAAU,EACZ,EAA2B,EAE3B,EAAc,EAAc,OAAO,KAAK,IAAI,CAElD,IAAIA,EACJ,MAAM,GAAyB,GAAG,KAChC,IAAgB,EAAY,KAAK,CAAC,UAC3B,EAAa,GAAG,EAAK,EAGxB,EAAc,CAClB,MACA,OACA,SACA,OACA,MACA,QACA,UACD,CAEKC,EAAmE,CAAE,YAAa,WAAY,CAU9FC,EAAmC,CACvC,QAAS,IACT,QAAS,CACP,YAAa,SACb,uBAAwB,EAAI,iBAAmB,KAChD,CACD,iBAAkB,GAAU,EAAsB,EAAQ,EAAmB,CAC7E,cAAe,CACb,mBAAoB,GACrB,CACD,UAAW,GACZ,CAEK,EAAuB,GAAwC,KAAK,EAAQ,QAAU,IAAI,aAAa,CAAC,IAAI,EAAQ,SAAW,qBAAqB,EAAQ,KAAO,iBAWnK,EAAsB,OAAO,SAAS,EAAI,qBAAuB,GAAI,GAAG,EAAI,IAElF,IAAqB,EAArB,KAA6B,CAC3B,GAYA,YAAY,EAA4B,EAAE,CAAE,CAC1C,MAAA,EAAe,EAAS,QAAU,GAAQ,CAC1C,KAAK,SAAW,EAAM,EAAiB,EAAS,CAC5C,KAAK,SAAS,WAChB,KAAK,SAAS,UAAY,IAAI,EAAU,CAAE,kBAAmB,EAAqB,CAAC,CACnF,KAAK,SAAS,WAAa,IAAI,EAAW,CAAE,kBAAmB,EAAqB,CAAC,CACrF,OAAO,KAAK,SAAS,WACZ,KAAK,SAAS,YAAc,KACrC,KAAK,SAAS,UAAY,IAAI,EAAU,CAAE,UAAW,GAAO,CAAC,CAC7D,KAAK,SAAS,WAAa,IAAI,EAAW,CAAE,UAAW,GAAO,CAAC,CAC/D,OAAO,KAAK,S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,YAAY,mBAQvD,IAA+B,CAC7B,EAAY,QAAS,GAAW,CAC9B,KAAK,IACH,GAAG,IACY,KAAK,MAAM,GAAQ,GAAG,EAAkE,EACzG,CAQJ,MAAa,YAAe,EAAa,EAAkB,EAAE,CAAgB,CAC3E,IAAMM,EAAqB,EAAE,CACzBC,EAAoC,KACpCC,EAAiC,KAE/B,EAAe,CAAE,OAAQ,CAAE,KAAM,EAAG,CAAE,GAAG,EAAS,CAGxD,IADA,EAAa,OAAO,OAAS,GACrB,EAAa,OAAO,OAAS,GAAK,IAAoB,IAAuB,IAAoB,GAAG,CAC1G,GAAM,CAAE,QAAS,MAAM,KAAK,IAAS,EAAK,EAAa,CACvD,EAAkB,EAAK,OACnB,EAAa,OAAO,OAAS,IAC/B,EAAqB,EAAK,QAG5B,EAAa,OAAO,MAAQ,EAC5B,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAGjD,OAAO,EAYT,MAAa,6BAAgC,EAAa,EAAkB,EAAE,CAAE,EAAY,IAAmB,CAC7G,IAAMF,EAAqB,EAAE,CAEzB,EAAoB,GACpB,EAAO,EACX,KAAO,IAAsB,IAAc,IAAM,EAAO,IAAY,CAClE,GAAM,CAAE,QAAS,MAAM,KAAK,KAAoC,EAAK,CACnE,GAAG,EACH,OACD,CAAC,CACI,CAAE,OAAM,SAAU,EACxB,GAAQ,EACR,MAAM,UAAU,KAAK,MAAM,EAAe,EAAK,CAC/C,EAAoB,EAAc,OAAS,EAG7C,OAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/network",
3
- "version": "1.8.18",
3
+ "version": "1.8.20-beta.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./lib/index.cjs",
@@ -21,6 +21,11 @@
21
21
  "files": [
22
22
  "lib"
23
23
  ],
24
+ "scripts": {
25
+ "test": "tsx --test",
26
+ "coverage": "tsx --test --experimental-test-coverage",
27
+ "build": "tsdown"
28
+ },
24
29
  "engines": {
25
30
  "node": ">=18"
26
31
  },
@@ -29,7 +34,7 @@
29
34
  "dependencies": {
30
35
  "@autofleet/axios-cache-adapter": "^2.7.3-hotfix-1",
31
36
  "agentkeepalive": "^4.6.0",
32
- "axios": "^0.30.2",
37
+ "axios": "catalog:",
33
38
  "axios-retry": "^4.5.0",
34
39
  "deepmerge": "^4.3.1",
35
40
  "qs": "^6.14.0"
@@ -38,15 +43,10 @@
38
43
  "@autofleet/logger": ">=4.2.0"
39
44
  },
40
45
  "devDependencies": {
46
+ "@autofleet/logger": "workspace:^",
41
47
  "@types/node": "^18.19.75",
42
48
  "@types/qs": "^6.9.18",
43
49
  "nock": "^14.0.1",
44
- "tsx": "^4.20.4",
45
- "@autofleet/logger": "^4.2.34"
46
- },
47
- "scripts": {
48
- "test": "tsx --test",
49
- "coverage": "tsx --test --experimental-test-coverage",
50
- "build": "tsdown"
50
+ "tsx": "^4.20.4"
51
51
  }
52
- }
52
+ }