diff --git a/README.md b/README.md index 3449559..f3d8560 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ which will be passed into `AxiosHarTracker` constructor: ```js const axiosTracker = new AxiosHarTracker(axios); ``` +The constructor takes an optional second object for creator configuration and an optional third argument ```maxEntries```, which will prevent +the log from growing beyond that size. In order to perform an actual request use the axios.get/post/delete... call, examples: diff --git a/src/axios-har-tracker.ts b/src/axios-har-tracker.ts index 55a2028..268e42f 100644 --- a/src/axios-har-tracker.ts +++ b/src/axios-har-tracker.ts @@ -42,15 +42,18 @@ export class AxiosHarTracker { private generatedHar: HarFile; private newEntry: NewEntry; private creatorConfig: AxiosHarTrackerCreatorConfig; + private maxEntries: number; constructor( axiosModule: AxiosInstance, creatorConfig: AxiosHarTrackerCreatorConfig = { name: "axios-har-tracker", version: "0.1.0", - } + }, + maxEntries?:number ) { this.axios = axiosModule; + this.maxEntries = maxEntries; this.creatorConfig = creatorConfig; this.resetHar(); @@ -64,6 +67,7 @@ export class AxiosHarTracker { if (error.request) { this.newEntry.request = this.returnRequestObject(error.request); this.generatedHar.log.entries.push(this.newEntry); + this.pruneLog(); } return Promise.reject(error); } @@ -163,6 +167,13 @@ export class AxiosHarTracker { private pushNewEntryResponse(response) { this.newEntry.response = this.returnResponseObject(response); this.generatedHar.log.entries.push(this.newEntry); + this.pruneLog(); + } + + private pruneLog() { + if (this.maxEntries !== undefined && this.generatedHar.log.entries?.length > this.maxEntries) { + this.generatedHar.log.entries.shift(); + } } private generateNewEntry() { diff --git a/src/tests/multiple-calls.spec.ts b/src/tests/multiple-calls.spec.ts index c8a0448..cb4c39e 100644 --- a/src/tests/multiple-calls.spec.ts +++ b/src/tests/multiple-calls.spec.ts @@ -102,7 +102,17 @@ describe("axios-har-tracker e2e tests", () => { await fse.writeJson("./harfiles/example-500.har", generatedHar); }); - it("Should collect multiple calls", async () => { + it("Should collect multiple calls up to a max of 4", async () => { + + axiosTracker = new AxiosHarTracker(axios, undefined, 4); + + //This one will get pruned + await axios.get("http://httpstat.us/200", { + params: { + test: 1, + }, + }); + await axios.get("http://httpstat.us/200"); try { await axios.get("http://httpstat.us/302"); @@ -125,8 +135,13 @@ describe("axios-har-tracker e2e tests", () => { "An expected error appears after call to http://httpstat.us/500" ); } + const generatedHar = axiosTracker.getGeneratedHar(); const array = generatedHar.log.entries; + + //5 requests were made but maxEntries is 4 + expect(array.length).toEqual(4); + expect(array[0].request).toMatchObject({ method: "get", url: "http://httpstat.us/200",