Skip to content

Commit 94e70f3

Browse files
Merge pull request #1268 from opencomponents/improve-events-handler-types
[IMPROVEMENT] Improve typings of events in events handler
2 parents b56787a + 8cf3f24 commit 94e70f3

File tree

8 files changed

+105
-70
lines changed

8 files changed

+105
-70
lines changed

src/cli/facade/dev.ts

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -124,19 +124,16 @@ const dev =
124124
const mockedPlugins = getMockedPlugins(logger, componentsDir);
125125
mockedPlugins.forEach(p => registry.register(p));
126126

127-
registry.on(
128-
'request',
129-
(data: { errorCode: string; errorDetails: string }) => {
130-
if (data.errorCode === 'PLUGIN_MISSING_FROM_REGISTRY') {
131-
logger.err(
132-
cliErrors.PLUGIN_MISSING_FROM_REGISTRY(
133-
data.errorDetails,
134-
colors.blue(strings.commands.cli.MOCK_PLUGIN)
135-
)
136-
);
137-
}
127+
registry.on('request', data => {
128+
if (data.errorCode === 'PLUGIN_MISSING_FROM_REGISTRY') {
129+
logger.err(
130+
cliErrors.PLUGIN_MISSING_FROM_REGISTRY(
131+
data.errorDetails!,
132+
colors.blue(strings.commands.cli.MOCK_PLUGIN)
133+
)
134+
);
138135
}
139-
);
136+
});
140137
};
141138

142139
logger.warn(cliMessages.SCANNING_COMPONENTS, true);

src/registry/domain/components-cache/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import _ from 'lodash';
22
import getComponentsList from './components-list';
3-
import * as eventsHandler from '../events-handler';
3+
import eventsHandler from '../events-handler';
44
import getUnixUTCTimestamp from 'oc-get-unix-utc-timestamp';
55
import { Cdn, ComponentsList, Config } from '../../../types';
66

src/registry/domain/components-details.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import async from 'async';
22
import _ from 'lodash';
3-
import * as eventsHandler from './events-handler';
3+
import eventsHandler from './events-handler';
44
import getUnixUTCTimestamp from 'oc-get-unix-utc-timestamp';
55
import {
66
Cdn,
@@ -16,7 +16,10 @@ export default function componentsDetails(conf: Config, cdn: Cdn) {
1616
message: string | Error,
1717
callback: (code: string) => void
1818
) => {
19-
eventsHandler.fire('error', { code, message });
19+
eventsHandler.fire('error', {
20+
code,
21+
message: (message as Error)?.message ?? message
22+
});
2023
return callback(code);
2124
};
2225

src/registry/domain/events-handler.ts

Lines changed: 73 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,86 @@
1+
import { IncomingHttpHeaders } from 'http';
12
import strings from '../../resources';
23

34
type Subscription<T = any> = (data: T) => void;
45
let subscriptions: Record<string, Array<Subscription>> = {};
56

6-
export function fire(eventName: string, eventData: unknown): void {
7-
if (subscriptions[eventName]) {
8-
subscriptions[eventName].forEach(callback => {
9-
callback(eventData);
10-
});
11-
}
7+
export interface RequestData {
8+
body: any;
9+
duration: number;
10+
headers: IncomingHttpHeaders;
11+
method: string;
12+
path: string;
13+
relativeUrl: string;
14+
query: Record<string, any>;
15+
url: string;
16+
statusCode: number;
17+
errorDetails?: string;
18+
errorCode?: string;
1219
}
1320

14-
export function on(eventName: string, callback: Subscription): void {
15-
if (typeof callback !== 'function') {
16-
throw strings.errors.registry.CONFIGURATION_ONREQUEST_MUST_BE_FUNCTION;
17-
}
21+
type Events = {
22+
error: { code: string; message: string };
23+
start: unknown;
24+
'cache-poll': number;
25+
request: RequestData;
26+
'component-retrieved': {
27+
headers: IncomingHttpHeaders;
28+
name: string;
29+
parameters: IncomingHttpHeaders;
30+
requestVersion: string;
31+
duration: number;
32+
};
33+
};
1834

19-
if (!subscriptions[eventName]) {
20-
subscriptions[eventName] = [];
21-
}
35+
type EventsHandler = {
36+
fire<T extends keyof Events>(eventName: T, data: Events[T]): void;
37+
on<T extends keyof Events>(
38+
eventName: T,
39+
listener: Subscription<Events[T]>
40+
): void;
41+
off<T extends keyof Events>(
42+
eventName: T,
43+
listener: Subscription<Events[T]>
44+
): void;
45+
reset(): void;
46+
};
2247

23-
subscriptions[eventName].push(callback);
24-
}
48+
const eventsHandler: EventsHandler = {
49+
fire(eventName: string, eventData: unknown): void {
50+
if (subscriptions[eventName]) {
51+
subscriptions[eventName].forEach(callback => {
52+
callback(eventData);
53+
});
54+
}
55+
},
2556

26-
export function off(eventName: string, callback: Subscription): void {
27-
if (typeof callback !== 'function') {
28-
throw strings.errors.registry.CONFIGURATION_OFFREQUEST_MUST_BE_FUNCTION;
29-
}
57+
on(eventName: string, callback: Subscription): void {
58+
if (typeof callback !== 'function') {
59+
throw strings.errors.registry.CONFIGURATION_ONREQUEST_MUST_BE_FUNCTION;
60+
}
61+
62+
if (!subscriptions[eventName]) {
63+
subscriptions[eventName] = [];
64+
}
3065

31-
if (subscriptions[eventName]) {
32-
subscriptions[eventName] = subscriptions[eventName].filter(
33-
sub => sub !== callback
34-
);
66+
subscriptions[eventName].push(callback);
67+
},
68+
69+
off(eventName: string, callback: Subscription): void {
70+
if (typeof callback !== 'function') {
71+
throw strings.errors.registry.CONFIGURATION_OFFREQUEST_MUST_BE_FUNCTION;
72+
}
73+
74+
if (subscriptions[eventName]) {
75+
subscriptions[eventName] = subscriptions[eventName].filter(
76+
sub => sub !== callback
77+
);
78+
}
79+
},
80+
81+
reset(): void {
82+
subscriptions = {};
3583
}
36-
}
84+
};
3785

38-
export function reset(): void {
39-
subscriptions = {};
40-
}
86+
export default eventsHandler;

src/registry/index.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import http from 'http';
55
import _ from 'lodash';
66

77
import appStart from './app-start';
8-
import * as eventsHandler from './domain/events-handler';
8+
import eventsHandler from './domain/events-handler';
99
import * as middleware from './middleware';
1010
import * as pluginsInitialiser from './domain/plugins-initialiser';
1111
import Repository from './domain/repository';
@@ -117,9 +117,12 @@ export default function registry(inputOptions: Input) {
117117
callback(null, { app, server });
118118
});
119119

120-
server.on('error', message => {
121-
eventsHandler.fire('error', { code: 'EXPRESS_ERROR', message });
122-
callback(message, undefined as any);
120+
server.on('error', error => {
121+
eventsHandler.fire('error', {
122+
code: 'EXPRESS_ERROR',
123+
message: error?.message ?? String(error)
124+
});
125+
callback(error, undefined as any);
123126
});
124127
}
125128
);

src/registry/middleware/request-handler.ts

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,11 @@
11
import { Request, RequestHandler, Response } from 'express';
2-
import { IncomingHttpHeaders } from 'http';
32
import responseTime from 'response-time';
43

5-
import * as eventsHandler from '../domain/events-handler';
6-
7-
interface ResponseTimeData {
8-
body: any;
9-
duration: number;
10-
headers: IncomingHttpHeaders;
11-
method: string;
12-
path: string;
13-
relativeUrl: string;
14-
query: Record<string, any>;
15-
url: string;
16-
statusCode: number;
17-
errorDetails?: string;
18-
errorCode?: string;
19-
}
4+
import eventsHandler, { RequestData } from '../domain/events-handler';
205

216
export default function requestHandler(): RequestHandler {
227
return responseTime((req: Request, res: Response, time) => {
23-
const data: ResponseTimeData = {
8+
const data: RequestData = {
249
body: req.body,
2510
duration: parseInt(String(time * 1000)),
2611
headers: req.headers,
@@ -32,12 +17,12 @@ export default function requestHandler(): RequestHandler {
3217
statusCode: res.statusCode
3318
};
3419

35-
if ((res as any).errorDetails) {
36-
data.errorDetails = (res as any).errorDetails;
20+
if (res.errorDetails) {
21+
data.errorDetails = res.errorDetails;
3722
}
3823

39-
if ((res as any).errorCode) {
40-
data.errorCode = (res as any).errorCode;
24+
if (res.errorCode) {
25+
data.errorCode = res.errorCode;
4126
}
4227

4328
eventsHandler.fire('request', data);

src/registry/routes/helpers/get-component.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import vm from 'vm';
77
import _ from 'lodash';
88

99
import applyDefaultValues from './apply-default-values';
10-
import * as eventsHandler from '../../domain/events-handler';
10+
import eventsHandler from '../../domain/events-handler';
1111
import GetComponentRetrievingInfo from './get-component-retrieving-info';
1212
import * as getComponentFallback from './get-component-fallback';
1313
import isTemplateLegacy from '../../../utils/is-template-legacy';

test/unit/registry-domain-events-handler.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@ const expect = require('chai').expect;
44
const sinon = require('sinon');
55

66
describe('registry : domain : events-handler', () => {
7-
const eventsHandler = require('../../dist/registry/domain/events-handler');
7+
const eventsHandler =
8+
require('../../dist/registry/domain/events-handler').default;
89

910
describe('when requiring it multiple times', () => {
1011
const spy = sinon.spy();
1112
let handler2;
1213

1314
before(() => {
1415
eventsHandler.on('eventName', spy);
15-
handler2 = require('../../dist/registry/domain/events-handler');
16+
handler2 = require('../../dist/registry/domain/events-handler').default;
1617
handler2.fire('eventName', { a: 1234 });
1718
});
1819

0 commit comments

Comments
 (0)