Skip to content

Commit bf5ed4b

Browse files
authored
Merge pull request #47 from sckv/change-default-timer
fix(request-time): make request time header optional
2 parents 0bbd8b1 + d1e52be commit bf5ed4b

File tree

5 files changed

+29
-23
lines changed

5 files changed

+29
-23
lines changed

src/__tests__/request.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ test('Adds logging listener if set up', () => {
3333

3434
const listeners = out.listenerCount('close');
3535

36-
new BareRequest(inc, out, true);
36+
new BareRequest(inc, out, { logging: true });
3737

3838
expect(out.listenerCount('close')).toBe(listeners + 1);
3939
});
@@ -49,7 +49,7 @@ test('Gets response header', () => {
4949
test('Adds basic headers to the request upon instantiation', () => {
5050
const { request } = createRequest();
5151

52-
expect(request.getHeader('Content-Type')).toBe('text/plain');
52+
expect(request.getHeader('Content-Type')).toBe('text/plain; charset=utf-8');
5353
expect(request.getHeader('X-Request-Id')).toEqual(expect.any(String));
5454
});
5555

src/__tests__/server.integration.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ test('Sets x-processing-time to milliseconds', async () => {
116116
});
117117

118118
test('Base x-processing-time is in seconds', async () => {
119-
const app = new BareHttp();
119+
const app = new BareHttp({ requestTimeFormat: 's' });
120120

121121
app.get({
122122
route: '/test',

src/bench/baretest.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ const brt = new BareHttp({ statisticsReport: true });
44

55
brt.get({
66
route: '/myroute',
7-
handler: () => 'just response',
7+
handler: (flow) => {
8+
flow._send('just response');
9+
},
810
});
911

1012
brt.start(() => console.log('server started'));

src/request.ts

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,10 @@ export class BareRequest {
5252
sent = false;
5353

5454
private cache = true;
55-
private startTime: [seconds: number, nanoseconds: number];
55+
private startTime?: [seconds: number, nanoseconds: number];
5656
private startDate = new Date();
5757
private remoteClient = '';
58-
private countTimeFormat: 'ms' | 's' = 's';
58+
private requestTimeFormat?: 'ms' | 's';
5959
private headers: { [header: string]: string | string[] } = {};
6060
private cookies: { [cooke: string]: string } = {};
6161
private contentType?: keyof typeof ContentType;
@@ -64,20 +64,27 @@ export class BareRequest {
6464
constructor(
6565
public _originalRequest: IncomingMessage,
6666
public _originalResponse: ServerResponse,
67-
logging?: boolean,
67+
options?: { logging?: boolean; requestTimeFormat?: 'ms' | 's' },
6868
) {
6969
this.ID = { code: (_originalRequest.headers['x-request-id'] as string) || generateId() };
7070
this.remoteIp = _originalRequest.socket.remoteAddress;
7171
this.contentType = this._originalRequest.headers['content-type'] as any;
7272
this.requestHeaders = this._originalRequest.headers;
7373

74-
_originalRequest['flow'] = this; // to receive an id later on in the route handler
74+
_originalRequest['flow'] = this; // to receive flow object later on in the route handler
7575

76-
this.setHeaders({ 'Content-Type': 'text/plain', 'X-Request-Id': this.ID.code });
77-
this.startTime = process.hrtime();
76+
this.setHeaders({
77+
'Content-Type': 'text/plain; charset=utf-8',
78+
'X-Request-Id': this.ID.code,
79+
});
80+
81+
if (options?.requestTimeFormat) {
82+
this.startTime = process.hrtime();
83+
this.requestTimeFormat = options.requestTimeFormat;
84+
}
7885

7986
// call logging section
80-
if (logging === true) {
87+
if (options?.logging === true) {
8188
_originalResponse.on('close', () =>
8289
logHttp(
8390
this.headers,
@@ -140,22 +147,20 @@ export class BareRequest {
140147
}
141148

142149
private setRequestTime() {
150+
if (!this.requestTimeFormat) return;
151+
143152
const diff = process.hrtime(this.startTime);
144153

145154
const time =
146-
diff[0] * (this.countTimeFormat === 's' ? 1 : 1e3) +
147-
diff[1] * (this.countTimeFormat === 's' ? 1e-9 : 1e-6);
155+
diff[0] * (this.requestTimeFormat === 's' ? 1 : 1e3) +
156+
diff[1] * (this.requestTimeFormat === 's' ? 1e-9 : 1e-6);
148157

149158
this.setHeaders({
150159
'X-Processing-Time': time,
151-
'X-Processing-Time-Mode': this.countTimeFormat === 's' ? 'seconds' : 'milliseconds',
160+
'X-Processing-Time-Mode': this.requestTimeFormat === 's' ? 'seconds' : 'milliseconds',
152161
});
153162
}
154163

155-
private setTimeFormat(format: 's' | 'ms') {
156-
this.countTimeFormat = format;
157-
}
158-
159164
private cleanHeader(header: string) {
160165
delete this.headers[header];
161166
}
@@ -245,7 +250,8 @@ export class BareRequest {
245250
logMe.error("Tying to send into closed client's stream");
246251
return;
247252
}
248-
if (this._originalResponse.headersSent) {
253+
254+
if (this._originalResponse.headersSent || this.sent) {
249255
logMe.error('Trying to send with the headers already sent');
250256
return;
251257
}

src/server.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ type BareOptions<A extends IP> = {
5353
errorHandlerMiddleware?: ErrorHandler;
5454
/**
5555
* Request time format in `seconds` or `milliseconds`
56-
* Default 's' - seconds
56+
* Default - disabled
5757
*/
5858
requestTimeFormat?: 's' | 'ms';
5959
/**
@@ -138,16 +138,14 @@ export class BareServer<A extends IP> {
138138
#listener = (request: IncomingMessage, response: ServerResponse) => {
139139
const { requestTimeFormat, logging } = this.bareOptions;
140140

141-
const flow = new BareRequest(request, response, logging);
141+
const flow = new BareRequest(request, response, { logging, requestTimeFormat });
142142

143143
// init and attach request uuid to the context
144144
if (this.bareOptions.context) {
145145
newContext('request');
146146
context.current?.store.set('id', flow.ID.code);
147147
}
148148

149-
if (requestTimeFormat) flow['setTimeFormat'](requestTimeFormat);
150-
151149
// attach a flow to the flow memory storage
152150
this.applyMiddlewares(flow).catch((e) => this.#errorHandler(e, flow, 400));
153151
};

0 commit comments

Comments
 (0)