Skip to content

Commit cd168f3

Browse files
committed
format code
1 parent f66b7aa commit cd168f3

File tree

3 files changed

+131
-116
lines changed

3 files changed

+131
-116
lines changed

packages/http/fetch/src/middlewares/compressionHandler.ts

+57-35
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,20 @@ import { CompressionHandlerOptions, CompressionHandlerOptionsKey } from "./optio
1818
export class CompressionHandler implements Middleware {
1919
next: Middleware | undefined;
2020

21+
/**
22+
* @private
23+
* @static
24+
* A member holding the name of content range header
25+
*/
26+
private static CONTENT_RANGE_HEADER = "Content-Range";
27+
28+
/**
29+
* @private
30+
* @static
31+
* A member holding the name of content encoding header
32+
*/
33+
private static CONTENT_ENCODING_HEADER = "Content-Encoding";
34+
2135
/**
2236
* @public
2337
* @constructor
@@ -58,7 +72,7 @@ export class CompressionHandler implements Middleware {
5872
return this.next?.execute(url, requestInit, requestOptions) ?? Promise.reject(new Error("Response is undefined"));
5973
}
6074

61-
span?.setAttribute("http.request_body_compressed", true);
75+
span?.setAttribute("http.request.body.compressed", true);
6276

6377
const unCompressedBody = await this.readBodyAsBytes(requestInit.body);
6478
const unCompressedBodySize = unCompressedBody.length;
@@ -68,20 +82,20 @@ export class CompressionHandler implements Middleware {
6882

6983
// add Content-Encoding to request header
7084
requestInit.headers = new Headers(requestInit.headers);
71-
requestInit.headers.set("Content-Encoding", "gzip");
85+
requestInit.headers.set(CompressionHandler.CONTENT_ENCODING_HEADER, "gzip");
7286
requestInit.body = compressedBody.body;
7387

74-
span?.setAttribute("http.request_content_length", compressedBody.size);
88+
span?.setAttribute("http.request.body.size", compressedBody.size);
7589

7690
// execute the next middleware and check if the response code is 415
7791
try {
7892
const response = await this.next?.execute(url, requestInit, requestOptions);
7993
if (response?.status === 415) {
8094
// remove the Content-Encoding header
81-
requestInit.headers.delete("Content-Encoding");
95+
requestInit.headers.delete(CompressionHandler.CONTENT_ENCODING_HEADER);
8296
requestInit.body = unCompressedBody.buffer;
83-
span?.setAttribute("http.request_body_compressed", false);
84-
span?.setAttribute("http.request_content_length", unCompressedBodySize);
97+
span?.setAttribute("http.request.body.compressed", false);
98+
span?.setAttribute("http.request.body.size", unCompressedBodySize);
8599

86100
return this.next?.execute(url, requestInit, requestOptions) ?? Promise.reject(new Error("Response is undefined"));
87101
}
@@ -95,12 +109,12 @@ export class CompressionHandler implements Middleware {
95109
return false;
96110
}
97111
if (header instanceof Headers) {
98-
const contentRange = header.get("Content-Range");
112+
const contentRange = header.get(CompressionHandler.CONTENT_RANGE_HEADER);
99113
if (contentRange) {
100114
return contentRange.toLowerCase().includes("bytes");
101115
}
102116
} else if (typeof header === "object") {
103-
const contentRange = (header as Record<string, string>)["Content-Range"];
117+
const contentRange = (header as Record<string, string>)[CompressionHandler.CONTENT_RANGE_HEADER];
104118
if (contentRange) {
105119
return contentRange.toLowerCase().includes("bytes");
106120
}
@@ -113,9 +127,9 @@ export class CompressionHandler implements Middleware {
113127
return false;
114128
}
115129
if (header instanceof Headers) {
116-
return header.has("Content-Encoding");
130+
return header.has(CompressionHandler.CONTENT_ENCODING_HEADER);
117131
} else if (typeof header === "object") {
118-
return "Content-Encoding" in header;
132+
return CompressionHandler.CONTENT_ENCODING_HEADER in header;
119133
}
120134
return false;
121135
}
@@ -139,29 +153,37 @@ export class CompressionHandler implements Middleware {
139153
throw new Error("Unsupported body type");
140154
}
141155

142-
143-
private compressReqBody(reqBody: Uint8Array): Promise<{ body: ReadableStream<Uint8Array>, size: number }> {
144-
return new Promise((resolve, reject) => {
145-
const buffer = new ArrayBuffer(reqBody.length);
146-
const gzipWriter = new CompressionStream('gzip');
147-
const writer = gzipWriter.writable.getWriter();
148-
149-
writer.write(reqBody).then(() => {
150-
writer.close().then(() => {
151-
const compressedStream = gzipWriter.readable;
152-
const reader = compressedStream.getReader();
153-
let size = 0;
154-
155-
reader.read().then(function process({ done, value }) {
156-
if (done) {
157-
resolve({ body: new Response(buffer).body!, size });
158-
return;
159-
}
160-
size += value.length;
161-
reader.read().then(process);
162-
}).catch(reject);
163-
}).catch(reject);
164-
}).catch(reject);
165-
});
166-
}
156+
private compressReqBody(reqBody: Uint8Array): Promise<{ body: ArrayBuffer; size: number }> {
157+
return new Promise((resolve, reject) => {
158+
const buffer = new ArrayBuffer(reqBody.length);
159+
const gzipWriter = new CompressionStream("gzip");
160+
const writer = gzipWriter.writable.getWriter();
161+
162+
writer
163+
.write(reqBody)
164+
.then(() => {
165+
writer
166+
.close()
167+
.then(() => {
168+
const compressedStream = gzipWriter.readable;
169+
const reader = compressedStream.getReader();
170+
let size = 0;
171+
172+
reader
173+
.read()
174+
.then(function process({ done, value }) {
175+
if (done) {
176+
resolve({ body: buffer, size });
177+
return;
178+
}
179+
size += value.length;
180+
reader.read().then(process);
181+
})
182+
.catch(reject);
183+
})
184+
.catch(reject);
185+
})
186+
.catch(reject);
187+
});
188+
}
167189
}

packages/http/fetch/src/middlewares/options/compressionHandlerOptions.ts

+22-27
Original file line numberDiff line numberDiff line change
@@ -20,37 +20,32 @@ export const CompressionHandlerOptionsKey = "CompressionHandlerOptionsKey";
2020
* Options for the compression handler.
2121
*/
2222
export class CompressionHandlerOptions implements RequestOption {
23-
private readonly _enableCompression: boolean;
24-
/**
25-
* Create a new instance of the CompressionHandlerOptions class
26-
* @param config the configuration to apply to the compression handler options.
27-
*/
28-
public constructor(config?: Partial<CompressionHandlerOptionsParams>) {
29-
if (config) {
30-
this._enableCompression = config.enableCompression ?? true;
31-
} else {
32-
this._enableCompression = true;
33-
}
34-
}
35-
/**
36-
* @inheritdoc
37-
*/
38-
public getKey(): string {
39-
return CompressionHandlerOptionsKey;
40-
}
41-
/**
42-
* Returns whether the compression handler is enabled or not.
43-
* @returns whether the compression handler is enabled or not.
44-
*/
45-
public get ShouldCompress(): boolean {
46-
return this._enableCompression;
47-
}
23+
private readonly _enableCompression: boolean;
24+
/**
25+
* Create a new instance of the CompressionHandlerOptions class
26+
* @param config the configuration to apply to the compression handler options.
27+
*/
28+
public constructor(config?: Partial<CompressionHandlerOptionsParams>) {
29+
this._enableCompression = config?.enableCompression ?? true;
30+
}
31+
/**
32+
* @inheritdoc
33+
*/
34+
public getKey(): string {
35+
return CompressionHandlerOptionsKey;
36+
}
37+
/**
38+
* Returns whether the compression handler is enabled or not.
39+
* @returns whether the compression handler is enabled or not.
40+
*/
41+
public get ShouldCompress(): boolean {
42+
return this._enableCompression;
43+
}
4844
}
4945

5046
/**
5147
* Parameters for the CompressionHandlerOptionsParams class constructor
5248
*/
5349
export interface CompressionHandlerOptionsParams {
54-
enableCompression: boolean;
50+
enableCompression: boolean;
5551
}
56-
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,76 @@
1-
2-
31
import { DummyFetchHandler } from "./dummyFetchHandler";
42
import { CompressionHandlerOptions } from "../../../src/middlewares/options/compressionHandlerOptions";
53
import { CompressionHandler } from "../../../src/middlewares/compressionHandler";
64

75
const defaultOptions = new CompressionHandlerOptions();
86

9-
import { assert, describe, it, expect, beforeEach, vi } from 'vitest';
7+
import { assert, describe, it, expect, beforeEach, vi } from "vitest";
108

11-
describe('CompressionHandler', () => {
12-
let compressionHandler: CompressionHandler;
13-
let nextMiddleware: DummyFetchHandler;
9+
describe("CompressionHandler", () => {
10+
let compressionHandler: CompressionHandler;
11+
let nextMiddleware: DummyFetchHandler;
1412

15-
beforeEach(() => {
16-
nextMiddleware = new DummyFetchHandler();
17-
compressionHandler = new CompressionHandler();
18-
compressionHandler.next = nextMiddleware;
19-
});
13+
beforeEach(() => {
14+
nextMiddleware = new DummyFetchHandler();
15+
compressionHandler = new CompressionHandler();
16+
compressionHandler.next = nextMiddleware;
17+
});
2018

21-
describe("constructor", () => {
22-
it("Should create an instance with given options", () => {
23-
const handler = new CompressionHandler(defaultOptions);
24-
assert.isDefined(handler["handlerOptions"]);
25-
});
19+
describe("constructor", () => {
20+
it("Should create an instance with given options", () => {
21+
const handler = new CompressionHandler(defaultOptions);
22+
assert.isDefined(handler["handlerOptions"]);
23+
});
2624

27-
it("Should create an instance with default set of options", () => {
28-
const handler = new CompressionHandler();
29-
assert.isDefined(handler["handlerOptions"]);
30-
});
31-
});
25+
it("Should create an instance with default set of options", () => {
26+
const handler = new CompressionHandler();
27+
assert.isDefined(handler["handlerOptions"]);
28+
});
29+
});
3230

33-
it('should throw an error if handlerOptions is undefined', () => {
34-
expect(() => new CompressionHandler(null as any)).toThrow('handlerOptions cannot be undefined');
35-
});
31+
it("should throw an error if handlerOptions is undefined", () => {
32+
expect(() => new CompressionHandler(null as any)).toThrow("handlerOptions cannot be undefined");
33+
});
3634

37-
it('should not compress if ShouldCompress is false', async () => {
38-
const options = new CompressionHandlerOptions({ enableCompression: false });
39-
compressionHandler = new CompressionHandler(options);
35+
it("should not compress if ShouldCompress is false", async () => {
36+
const options = new CompressionHandlerOptions({ enableCompression: false });
37+
compressionHandler = new CompressionHandler(options);
4038

41-
compressionHandler.next = nextMiddleware;
42-
vi.spyOn(nextMiddleware, 'execute');
43-
nextMiddleware.setResponses([new Response("ok", { status: 200 })]);
39+
compressionHandler.next = nextMiddleware;
40+
vi.spyOn(nextMiddleware, "execute");
41+
nextMiddleware.setResponses([new Response("ok", { status: 200 })]);
4442

45-
const requestInit = { headers: new Headers(), body: 'test' };
46-
const response = await compressionHandler.execute('http://example.com', requestInit);
43+
const requestInit = { headers: new Headers(), body: "test" };
44+
const response = await compressionHandler.execute("http://example.com", requestInit);
4745

48-
expect(requestInit.headers.has('Content-Encoding')).toBe(false);
49-
expect(nextMiddleware.execute).toHaveBeenCalled();
50-
expect(response).toBeInstanceOf(Response);
51-
});
46+
expect(requestInit.headers.has("Content-Encoding")).toBe(false);
47+
expect(nextMiddleware.execute).toHaveBeenCalled();
48+
expect(response).toBeInstanceOf(Response);
49+
});
5250

53-
it('should compress the request body if ShouldCompress is true', async () => {
54-
const options = new CompressionHandlerOptions({ enableCompression: true });
55-
compressionHandler = new CompressionHandler(options);
51+
it("should compress the request body if ShouldCompress is true", async () => {
52+
const options = new CompressionHandlerOptions({ enableCompression: true });
53+
compressionHandler = new CompressionHandler(options);
5654

57-
const requestInit = { headers: new Headers(), body: 'test' };
58-
await compressionHandler.execute('http://example.com', requestInit);
55+
const requestInit = { headers: new Headers(), body: "test" };
56+
await compressionHandler.execute("http://example.com", requestInit);
5957

60-
expect(requestInit.headers.get('Content-Encoding')).toBe('gzip');
61-
});
58+
expect(requestInit.headers.get("Content-Encoding")).toBe("gzip");
59+
});
6260

63-
it('should handle 415 response and retry without compression', async () => {
64-
const options = new CompressionHandlerOptions({ enableCompression: true });
65-
compressionHandler = new CompressionHandler(options);
61+
it("should handle 415 response and retry without compression", async () => {
62+
const options = new CompressionHandlerOptions({ enableCompression: true });
63+
compressionHandler = new CompressionHandler(options);
6664

67-
compressionHandler.next = nextMiddleware;
68-
nextMiddleware.setResponses([new Response("nope", { status: 415 }), new Response("ok", { status: 200 })]);
65+
compressionHandler.next = nextMiddleware;
66+
nextMiddleware.setResponses([new Response("nope", { status: 415 }), new Response("ok", { status: 200 })]);
6967

70-
//(nextMiddleware.execute as any).mockResolvedValueOnce(new Response(null, { status: 415 }));
68+
//(nextMiddleware.execute as any).mockResolvedValueOnce(new Response(null, { status: 415 }));
7169

72-
const requestInit = { headers: new Headers(), body: 'test' };
73-
const response = await compressionHandler.execute('http://example.com', requestInit);
70+
const requestInit = { headers: new Headers(), body: "test" };
71+
const response = await compressionHandler.execute("http://example.com", requestInit);
7472

75-
expect(requestInit.headers.has('Content-Encoding')).toBe(false);
76-
expect(response).toBeInstanceOf(Response);
77-
});
73+
expect(requestInit.headers.has("Content-Encoding")).toBe(false);
74+
expect(response).toBeInstanceOf(Response);
75+
});
7876
});

0 commit comments

Comments
 (0)