@autofleet/network 1.8.20-beta.0 → 1.9.1

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/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @autofleet/network
2
+
3
+ HTTP client wrapper built on Axios with keep-alive connection pooling, caching, retry logic, and logging support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @autofleet/network
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import Network from '@autofleet/network';
15
+
16
+ const client = new Network({
17
+ serviceName: 'my-service', // or serviceUrl: 'http://api.example.com'
18
+ timeout: 10000,
19
+ logger: myLogger, // optional
20
+ retries: 3, // optional, default: 0
21
+ });
22
+
23
+ // Make requests
24
+ const response = await client.get('/endpoint');
25
+ await client.post('/data', { payload });
26
+ ```
27
+
28
+ ## Features
29
+
30
+ - **Keep-alive connections** - Persistent HTTP/HTTPS connections with configurable socket timeout (default: 5s)
31
+ - **Request caching** - Cache responses with configurable TTL and invalidation
32
+ - **Automatic retries** - Exponential backoff retry logic with `axios-retry`
33
+ - **Logging** - Request/response logging via `@autofleet/logger`
34
+ - **Pagination helpers** - `getAllPages()` and `getAllPagesFromQueryEndpoint()` methods
35
+
36
+ ## Configuration
37
+
38
+ ### NetworkSettings
39
+
40
+ ```typescript
41
+ {
42
+ serviceName?: string; // Service name for K8s DNS resolution
43
+ serviceUrl?: string; // Direct URL (alternative to serviceName)
44
+ keepAlive?: boolean; // Enable keep-alive (default: true)
45
+ timeout?: number; // Request timeout in ms (default: 10000)
46
+ logger?: LoggerInstanceManager;
47
+ retries?: number; // Number of retry attempts
48
+ cache?: IAxiosCacheAdapterOptions; // Cache configuration
49
+ }
50
+ ```
51
+
52
+ ### Environment Variables
53
+
54
+ - `FREE_SOCKET_TIMEOUT` - Keep-alive socket timeout in ms (default: 5000)
55
+ - `NETWORK_ALLOW_KEEPALIVE_FALSE` - **[v1.9.0+]** Set to `'true'` to truly disable keep-alive when using `keepAlive: false`
56
+
57
+ ## Breaking Changes
58
+
59
+ ### v1.9.0
60
+ Node.js 20+ enables keep-alive by default, which meant `keepAlive: false` had no effect. Starting in v1.9.0, you can now explicitly disable keep-alive by setting both `keepAlive: false` and the environment variable `NETWORK_ALLOW_KEEPALIVE_FALSE=true`. This prevents silent performance degradation for services that unknowingly relied on keep-alive connections.
61
+ Will be used without this setting by default in v2.0.0
62
+
63
+ ## License
64
+
65
+ Proprietary
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.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;
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&&process.env.NETWORK_ALLOW_KEEPALIVE_FALSE===`true`&&(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 } 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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G,EAAS,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,IAAMQ,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"}
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\n/**\n * Network client configuration settings\n */\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n /** Service name for Kubernetes DNS resolution (e.g., 'EXAMPLE_MS' resolves to EXAMPLE_MS_SERVICE_HOST) */\n serviceName?: string;\n /** Direct service URL (alternative to serviceName) */\n serviceUrl?: string;\n /**\n * Enable HTTP keep-alive connections (default: true)\n * @since 1.9.0 - To disable keep-alive, set to false AND set env var NETWORK_ALLOW_KEEPALIVE_FALSE=true\n */\n keepAlive?: boolean;\n /** Logger instance for request/response logging */\n logger?: LoggerInstanceManager;\n /** Request timeout in milliseconds (default: 10000) */\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\n/**\n * HTTP client wrapper built on Axios with keep-alive connection pooling, caching, retry logic, and logging.\n *\n * @example\n * ```typescript\n * const client = new Network({\n * serviceName: 'EXAMPLE_MS',\n * timeout: 10000,\n * retries: 3\n * });\n *\n * const response = await client.get('/endpoint');\n * await client.post('/data', { payload });\n * ```\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\n // Configure keep-alive behavior\n if (this.settings.keepAlive) {\n // Enable keep-alive with custom free socket timeout\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 && process.env.NETWORK_ALLOW_KEEPALIVE_FALSE === 'true') {\n // [v1.9.0] Explicitly disable keep-alive\n // Node.js 20+ has keep-alive enabled by default, so we need to explicitly set keepAlive: false\n // This env var is required to prevent silent performance degradation in services that unknowingly relied on keep-alive\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 * Fetches all pages from a paginated API endpoint using page-based pagination.\n * Continues fetching until the response size differs from the first page or returns empty.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional Axios request options to include (e.g., headers, params).\n * @returns A promise that resolves to an array of all results from all pages.\n *\n * @example\n * ```typescript\n * const allUsers = await client.getAllPages<User>('/users', {\n * params: { status: 'active' }\n * });\n * ```\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 that uses POST requests with `{ rows, count }` response format.\n * Continues fetching until all results are retrieved or the optional page limit is reached.\n *\n * @param url The endpoint URL to send POST requests to.\n * @param options Additional options to include in the request payload (merged with page number).\n * @param pageLimit The maximum number of pages to fetch (default: 100). Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results from all pages.\n *\n * @example\n * ```typescript\n * const allOrders = await client.getAllPagesFromQueryEndpoint<Order>('/orders/query', {\n * filters: { status: 'pending' }\n * }, 50);\n * ```\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,CAqB9FC,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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D,OAAO,EAmBT,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/lib/index.d.cts CHANGED
@@ -13,13 +13,39 @@ declare module "axios" {
13
13
  "axios-retry"?: IAxiosRetryConfigExtended;
14
14
  }
15
15
  }
16
+ /**
17
+ * Network client configuration settings
18
+ */
16
19
  interface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {
20
+ /** Service name for Kubernetes DNS resolution (e.g., 'EXAMPLE_MS' resolves to EXAMPLE_MS_SERVICE_HOST) */
17
21
  serviceName?: string;
22
+ /** Direct service URL (alternative to serviceName) */
18
23
  serviceUrl?: string;
24
+ /**
25
+ * Enable HTTP keep-alive connections (default: true)
26
+ * @since 1.9.0 - To disable keep-alive, set to false AND set env var NETWORK_ALLOW_KEEPALIVE_FALSE=true
27
+ */
19
28
  keepAlive?: boolean;
29
+ /** Logger instance for request/response logging */
20
30
  logger?: LoggerInstanceManager;
31
+ /** Request timeout in milliseconds (default: 10000) */
21
32
  timeout?: number;
22
33
  }
34
+ /**
35
+ * HTTP client wrapper built on Axios with keep-alive connection pooling, caching, retry logic, and logging.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const client = new Network({
40
+ * serviceName: 'EXAMPLE_MS',
41
+ * timeout: 10000,
42
+ * retries: 3
43
+ * });
44
+ *
45
+ * const response = await client.get('/endpoint');
46
+ * await client.post('/data', { payload });
47
+ * ```
48
+ */
23
49
  declare class Network {
24
50
  #private;
25
51
  private readonly settings;
@@ -33,19 +59,36 @@ declare class Network {
33
59
  options: AxiosInstance["options"];
34
60
  constructor(settings?: NetworkSettings);
35
61
  /**
62
+ * Fetches all pages from a paginated API endpoint using page-based pagination.
63
+ * Continues fetching until the response size differs from the first page or returns empty.
64
+ *
36
65
  * @param url The endpoint URL to send the request to.
37
- * @param options Additional options to include in the request payload.
38
- * @returns A promise that resolves to an array of all results.
66
+ * @param options Additional Axios request options to include (e.g., headers, params).
67
+ * @returns A promise that resolves to an array of all results from all pages.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const allUsers = await client.getAllPages<User>('/users', {
72
+ * params: { status: 'active' }
73
+ * });
74
+ * ```
39
75
  */
40
76
  getAllPages<T>(url: string, options?: object): Promise<T[]>;
41
77
  /**
42
- * Fetches all pages from a paginated API endpoint until all results are retrieved
43
- * or an optional page limit is reached.
78
+ * Fetches all pages from a paginated API endpoint that uses POST requests with `{ rows, count }` response format.
79
+ * Continues fetching until all results are retrieved or the optional page limit is reached.
44
80
  *
45
- * @param url The endpoint URL to send the request to.
46
- * @param options Additional options to include in the request payload.
47
- * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.
48
- * @returns A promise that resolves to an array of all results.
81
+ * @param url The endpoint URL to send POST requests to.
82
+ * @param options Additional options to include in the request payload (merged with page number).
83
+ * @param pageLimit The maximum number of pages to fetch (default: 100). Set to -1 for no limit.
84
+ * @returns A promise that resolves to an array of all results from all pages.
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const allOrders = await client.getAllPagesFromQueryEndpoint<Order>('/orders/query', {
89
+ * filters: { status: 'pending' }
90
+ * }, 50);
91
+ * ```
49
92
  */
50
93
  getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
51
94
  }
package/lib/index.d.ts CHANGED
@@ -13,13 +13,39 @@ declare module "axios" {
13
13
  "axios-retry"?: IAxiosRetryConfigExtended;
14
14
  }
15
15
  }
16
+ /**
17
+ * Network client configuration settings
18
+ */
16
19
  interface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {
20
+ /** Service name for Kubernetes DNS resolution (e.g., 'EXAMPLE_MS' resolves to EXAMPLE_MS_SERVICE_HOST) */
17
21
  serviceName?: string;
22
+ /** Direct service URL (alternative to serviceName) */
18
23
  serviceUrl?: string;
24
+ /**
25
+ * Enable HTTP keep-alive connections (default: true)
26
+ * @since 1.9.0 - To disable keep-alive, set to false AND set env var NETWORK_ALLOW_KEEPALIVE_FALSE=true
27
+ */
19
28
  keepAlive?: boolean;
29
+ /** Logger instance for request/response logging */
20
30
  logger?: LoggerInstanceManager;
31
+ /** Request timeout in milliseconds (default: 10000) */
21
32
  timeout?: number;
22
33
  }
34
+ /**
35
+ * HTTP client wrapper built on Axios with keep-alive connection pooling, caching, retry logic, and logging.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const client = new Network({
40
+ * serviceName: 'EXAMPLE_MS',
41
+ * timeout: 10000,
42
+ * retries: 3
43
+ * });
44
+ *
45
+ * const response = await client.get('/endpoint');
46
+ * await client.post('/data', { payload });
47
+ * ```
48
+ */
23
49
  declare class Network {
24
50
  #private;
25
51
  private readonly settings;
@@ -33,19 +59,36 @@ declare class Network {
33
59
  options: AxiosInstance["options"];
34
60
  constructor(settings?: NetworkSettings);
35
61
  /**
62
+ * Fetches all pages from a paginated API endpoint using page-based pagination.
63
+ * Continues fetching until the response size differs from the first page or returns empty.
64
+ *
36
65
  * @param url The endpoint URL to send the request to.
37
- * @param options Additional options to include in the request payload.
38
- * @returns A promise that resolves to an array of all results.
66
+ * @param options Additional Axios request options to include (e.g., headers, params).
67
+ * @returns A promise that resolves to an array of all results from all pages.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const allUsers = await client.getAllPages<User>('/users', {
72
+ * params: { status: 'active' }
73
+ * });
74
+ * ```
39
75
  */
40
76
  getAllPages<T>(url: string, options?: object): Promise<T[]>;
41
77
  /**
42
- * Fetches all pages from a paginated API endpoint until all results are retrieved
43
- * or an optional page limit is reached.
78
+ * Fetches all pages from a paginated API endpoint that uses POST requests with `{ rows, count }` response format.
79
+ * Continues fetching until all results are retrieved or the optional page limit is reached.
44
80
  *
45
- * @param url The endpoint URL to send the request to.
46
- * @param options Additional options to include in the request payload.
47
- * @param pageLimit The maximum number of pages to fetch. Set to -1 for no limit.
48
- * @returns A promise that resolves to an array of all results.
81
+ * @param url The endpoint URL to send POST requests to.
82
+ * @param options Additional options to include in the request payload (merged with page number).
83
+ * @param pageLimit The maximum number of pages to fetch (default: 100). Set to -1 for no limit.
84
+ * @returns A promise that resolves to an array of all results from all pages.
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const allOrders = await client.getAllPagesFromQueryEndpoint<Order>('/orders/query', {
89
+ * filters: { status: 'pending' }
90
+ * }, 50);
91
+ * ```
49
92
  */
50
93
  getAllPagesFromQueryEndpoint<T>(url: string, options?: object, pageLimit?: number): Promise<T[]>;
51
94
  }
package/lib/index.js CHANGED
@@ -1,2 +1,2 @@
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};
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&&process.env.NETWORK_ALLOW_KEEPALIVE_FALSE===`true`&&(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 } 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,SAA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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\n/**\n * Network client configuration settings\n */\ninterface NetworkSettings extends CreateAxiosDefaults, IAxiosRetryConfig {\n /** Service name for Kubernetes DNS resolution (e.g., 'EXAMPLE_MS' resolves to EXAMPLE_MS_SERVICE_HOST) */\n serviceName?: string;\n /** Direct service URL (alternative to serviceName) */\n serviceUrl?: string;\n /**\n * Enable HTTP keep-alive connections (default: true)\n * @since 1.9.0 - To disable keep-alive, set to false AND set env var NETWORK_ALLOW_KEEPALIVE_FALSE=true\n */\n keepAlive?: boolean;\n /** Logger instance for request/response logging */\n logger?: LoggerInstanceManager;\n /** Request timeout in milliseconds (default: 10000) */\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\n/**\n * HTTP client wrapper built on Axios with keep-alive connection pooling, caching, retry logic, and logging.\n *\n * @example\n * ```typescript\n * const client = new Network({\n * serviceName: 'EXAMPLE_MS',\n * timeout: 10000,\n * retries: 3\n * });\n *\n * const response = await client.get('/endpoint');\n * await client.post('/data', { payload });\n * ```\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\n // Configure keep-alive behavior\n if (this.settings.keepAlive) {\n // Enable keep-alive with custom free socket timeout\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 && process.env.NETWORK_ALLOW_KEEPALIVE_FALSE === 'true') {\n // [v1.9.0] Explicitly disable keep-alive\n // Node.js 20+ has keep-alive enabled by default, so we need to explicitly set keepAlive: false\n // This env var is required to prevent silent performance degradation in services that unknowingly relied on keep-alive\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 * Fetches all pages from a paginated API endpoint using page-based pagination.\n * Continues fetching until the response size differs from the first page or returns empty.\n *\n * @param url The endpoint URL to send the request to.\n * @param options Additional Axios request options to include (e.g., headers, params).\n * @returns A promise that resolves to an array of all results from all pages.\n *\n * @example\n * ```typescript\n * const allUsers = await client.getAllPages<User>('/users', {\n * params: { status: 'active' }\n * });\n * ```\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 that uses POST requests with `{ rows, count }` response format.\n * Continues fetching until all results are retrieved or the optional page limit is reached.\n *\n * @param url The endpoint URL to send POST requests to.\n * @param options Additional options to include in the request payload (merged with page number).\n * @param pageLimit The maximum number of pages to fetch (default: 100). Set to -1 for no limit.\n * @returns A promise that resolves to an array of all results from all pages.\n *\n * @example\n * ```typescript\n * const allOrders = await client.getAllPagesFromQueryEndpoint<Order>('/orders/query', {\n * filters: { status: 'pending' }\n * }, 50);\n * ```\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,CAqB9FC,EAAmC,CACvC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AS,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,EAmBT,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.20-beta.0",
3
+ "version": "1.9.1",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./lib/index.cjs",
@@ -21,11 +21,6 @@
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
- },
29
24
  "engines": {
30
25
  "node": ">=18"
31
26
  },
@@ -34,7 +29,7 @@
34
29
  "dependencies": {
35
30
  "@autofleet/axios-cache-adapter": "^2.7.3-hotfix-1",
36
31
  "agentkeepalive": "^4.6.0",
37
- "axios": "catalog:",
32
+ "axios": "^0.30.2",
38
33
  "axios-retry": "^4.5.0",
39
34
  "deepmerge": "^4.3.1",
40
35
  "qs": "^6.14.0"
@@ -43,10 +38,15 @@
43
38
  "@autofleet/logger": ">=4.2.0"
44
39
  },
45
40
  "devDependencies": {
46
- "@autofleet/logger": "workspace:^",
47
41
  "@types/node": "^18.19.75",
48
42
  "@types/qs": "^6.9.18",
49
43
  "nock": "^14.0.1",
50
- "tsx": "^4.20.4"
44
+ "tsx": "^4.20.4",
45
+ "@autofleet/logger": "^4.2.35"
46
+ },
47
+ "scripts": {
48
+ "test": "tsx --test",
49
+ "coverage": "tsx --test --experimental-test-coverage",
50
+ "build": "tsdown"
51
51
  }
52
- }
52
+ }