Skip to content

Commit 19ee58b

Browse files
committed
fix(di): remove unused DIContext.runInContext and emit methods
BREAKING CHANGE: DIContext.runInContext and DIContext.emit methods are removed. Use runInContext and $emit function instead.
1 parent cdcae93 commit 19ee58b

File tree

12 files changed

+86
-212
lines changed

12 files changed

+86
-212
lines changed
+7-126
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1+
import {logger} from "../fn/logger.js";
12
import {DITest} from "../services/DITest.js";
23
import {bindContext, getAsyncStore} from "../utils/asyncHookContext.js";
34
import {DIContext} from "./DIContext.js";
45

56
describe("DIContext", () => {
67
beforeEach(() => DITest.create());
8+
beforeEach(() => {
9+
vi.spyOn(logger(), "info").mockReturnValue(undefined);
10+
});
711
afterEach(() => DITest.reset());
812
describe("constructor", () => {
913
it("should create a new Context and skip log", () => {
10-
const logger = {
11-
info: vi.fn()
12-
};
1314
const context = new DIContext({
1415
event: {
1516
response: {},
@@ -18,9 +19,7 @@ describe("DIContext", () => {
1819
}
1920
},
2021
id: "id",
21-
logger,
22-
maxStackSize: 0,
23-
injector: DITest.injector
22+
maxStackSize: 0
2423
});
2524

2625
expect(context.id).toEqual("id");
@@ -31,23 +30,17 @@ describe("DIContext", () => {
3130

3231
context.logger.info("test");
3332

34-
expect(logger.info).toHaveBeenCalled();
33+
expect(logger().info).toHaveBeenCalled();
3534

3635
context.destroy();
3736
});
3837
it("should create a new Context and log event", () => {
39-
const logger = {
40-
info: vi.fn()
41-
};
42-
4338
const context = new DIContext({
4439
id: "id",
4540
event: {
4641
response: {},
4742
request: {url: "/"}
4843
},
49-
logger,
50-
injector: DITest.injector,
5144
maxStackSize: 0,
5245
platform: "OTHER"
5346
});
@@ -63,7 +56,7 @@ describe("DIContext", () => {
6356
context.next();
6457
context.logger.info("test");
6558

66-
expect(logger.info).toHaveBeenCalled();
59+
expect(logger().info).toHaveBeenCalled();
6760
});
6861
});
6962

@@ -75,11 +68,7 @@ describe("DIContext", () => {
7568
request: {url: "/admin"}
7669
},
7770
id: "id",
78-
logger: {
79-
info: vi.fn()
80-
},
8171
maxStackSize: 0,
82-
injector: {emit: vi.fn()} as any,
8372
ignoreUrlPatterns: ["/admin", /\/admin2/]
8473
});
8574
const resolver = vi.fn().mockReturnValue("test");
@@ -100,11 +89,7 @@ describe("DIContext", () => {
10089
request: {url: "/admin"}
10190
},
10291
id: "id",
103-
logger: {
104-
info: vi.fn()
105-
},
10692
maxStackSize: 0,
107-
injector: {emit: vi.fn()} as any,
10893
ignoreUrlPatterns: ["/admin", /\/admin2/]
10994
});
11095
const resolver = vi.fn().mockResolvedValue("test");
@@ -116,108 +101,4 @@ describe("DIContext", () => {
116101
expect(resolver).toHaveBeenCalledTimes(1);
117102
});
118103
});
119-
describe("emit()", () => {
120-
it("should emit event", async () => {
121-
const context = new DIContext({
122-
event: {
123-
response: {},
124-
request: {url: "/admin"}
125-
},
126-
id: "id",
127-
logger: {
128-
info: vi.fn()
129-
},
130-
maxStackSize: 0,
131-
injector: {emit: vi.fn()} as any,
132-
ignoreUrlPatterns: ["/admin", /\/admin2/]
133-
});
134-
135-
await context.emit("event", "test");
136-
137-
expect(context.injector.emit).toHaveBeenCalledWith("event", "test");
138-
});
139-
});
140-
describe("runInContext()", () => {
141-
it("should run handler in a context", async () => {
142-
const context = new DIContext({
143-
event: {
144-
response: {},
145-
request: {url: "/admin"}
146-
},
147-
id: "id",
148-
logger: {
149-
info: vi.fn()
150-
},
151-
maxStackSize: 0,
152-
injector: {
153-
alterAsync: vi.fn().mockImplementation((event, fn, $ctx) => {
154-
return fn;
155-
})
156-
} as any,
157-
ignoreUrlPatterns: ["/admin", /\/admin2/]
158-
});
159-
160-
const stub = vi.fn();
161-
162-
await context.runInContext(stub);
163-
164-
expect(stub).toHaveBeenCalledWith();
165-
expect(context.injector.alterAsync).toHaveBeenCalledWith("$alterRunInContext", stub);
166-
});
167-
it("should run handler in a context + bind", async () => {
168-
const context = new DIContext({
169-
event: {
170-
response: {},
171-
request: {url: "/admin"}
172-
},
173-
id: "id",
174-
logger: {
175-
info: vi.fn()
176-
},
177-
maxStackSize: 0,
178-
injector: {
179-
alterAsync: vi.fn().mockImplementation((event, fn, $ctx) => {
180-
return fn;
181-
})
182-
} as any,
183-
ignoreUrlPatterns: ["/admin", /\/admin2/]
184-
});
185-
186-
const stub = vi.fn();
187-
188-
await context.runInContext(() => {
189-
bindContext(stub)();
190-
expect(getAsyncStore().getStore()).toEqual({current: context});
191-
});
192-
193-
expect(stub).toHaveBeenCalledWith();
194-
expect(context.injector.alterAsync).toHaveBeenCalledWith("$alterRunInContext", expect.any(Function));
195-
});
196-
it("should run handler in a context and fallback to next", async () => {
197-
const context = new DIContext({
198-
event: {
199-
response: {},
200-
request: {url: "/admin"}
201-
},
202-
id: "id",
203-
logger: {
204-
info: vi.fn()
205-
},
206-
maxStackSize: 0,
207-
injector: {
208-
alterAsync: vi.fn().mockImplementation((event, fn, $ctx) => {
209-
return null;
210-
})
211-
} as any,
212-
ignoreUrlPatterns: ["/admin", /\/admin2/]
213-
});
214-
215-
const stub = vi.fn();
216-
217-
await context.runInContext(stub);
218-
219-
expect(stub).toHaveBeenCalledWith();
220-
expect(context.injector.alterAsync).toHaveBeenCalledWith("$alterRunInContext", stub);
221-
});
222-
});
223104
});

packages/di/src/node/domain/DIContext.ts

+16-11
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
import {InjectorService, LocalsContainer} from "../../common/index.js";
1+
import {injector, InjectorService, LocalsContainer} from "../../common/index.js";
2+
import {logger} from "../fn/logger.js";
23
import {runInContext} from "../utils/asyncHookContext.js";
34
import {ContextLogger, ContextLoggerOptions} from "./ContextLogger.js";
45

56
export interface DIContextOptions extends Omit<ContextLoggerOptions, "dateStart"> {
67
id: string;
7-
injector: InjectorService;
8-
logger: any;
98
platform?: string;
109
}
1110

1211
export class DIContext {
1312
[x: string]: any;
13+
1414
readonly PLATFORM: string = "DI";
1515
#container?: LocalsContainer;
1616
#cache?: Map<any, any>;
@@ -24,7 +24,12 @@ export class DIContext {
2424
* Logger attached to the context request.
2525
*/
2626
get logger() {
27-
this.#logger = this.#logger || new ContextLogger(this.opts);
27+
this.#logger =
28+
this.#logger ||
29+
new ContextLogger({
30+
...this.opts,
31+
logger: logger()
32+
});
2833
return this.#logger;
2934
}
3035

@@ -61,7 +66,7 @@ export class DIContext {
6166
}
6267

6368
get injector(): InjectorService {
64-
return this.opts.injector!;
69+
return injector();
6570
}
6671

6772
get env() {
@@ -79,13 +84,13 @@ export class DIContext {
7984
return Promise.all([this.#container?.destroy(), this.#logger?.flush(true)]);
8085
}
8186

82-
emit(eventName: string, ...args: any[]) {
83-
return this.injector?.emit(eventName, ...args);
84-
}
87+
// emit(eventName: string, ...args: any[]) {
88+
// return $emit(eventName, ...args);
89+
// }
8590

86-
runInContext<Result = unknown>(next: (...args: unknown[]) => Result): Promise<Result> {
87-
return runInContext<Result>(this, next);
88-
}
91+
// runInContext<Result = unknown>(next: (...args: unknown[]) => Result): Promise<Result> {
92+
// return runInContext<Result>(this, next);
93+
// }
8994

9095
cache<Value = any>(key: string, cb: () => Value): Value {
9196
if (!this.has(key)) {
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,33 @@
11
import {OptimisticLockError} from "@mikro-orm/core";
2-
import {Logger} from "@tsed/logger";
3-
import {PlatformContext} from "@tsed/platform-http";
42
import {PlatformTest} from "@tsed/platform-http/testing";
5-
import {instance, mock, objectContaining, reset, spy, verify} from "ts-mockito";
63

74
import {OptimisticLockErrorFilter} from "./OptimisticLockErrorFilter.js";
85

96
describe("OptimisticLockErrorFilter", () => {
10-
const mockedLogger: Logger = mock<Logger>();
11-
let optimisticLockErrorFilter!: OptimisticLockErrorFilter;
12-
13-
beforeEach(() => {
14-
optimisticLockErrorFilter = new OptimisticLockErrorFilter();
15-
16-
return PlatformTest.create();
17-
});
18-
19-
afterEach(() => {
20-
reset(mockedLogger);
21-
22-
return PlatformTest.reset();
23-
});
7+
beforeEach(() => PlatformTest.create());
8+
afterEach(() => PlatformTest.reset());
249

2510
describe("catch", () => {
26-
it("should set HTTP status to 409", () => {
11+
it("should set HTTP status to 409", async () => {
12+
const optimisticLockErrorFilter = await PlatformTest.invoke(OptimisticLockErrorFilter);
13+
2714
// arrange
2815
const exception = OptimisticLockError.lockFailed("entity");
29-
const response = PlatformTest.createResponse();
30-
const request = PlatformTest.createRequest({
31-
url: "/admin"
32-
});
33-
const context = new PlatformContext({
34-
event: {
35-
response,
36-
request
37-
},
38-
id: "id",
39-
logger: instance(mockedLogger),
40-
maxStackSize: 0,
41-
injector: PlatformTest.injector
42-
});
43-
const spiedResponse = spy(response);
16+
const context = PlatformTest.createRequestContext();
17+
18+
vi.spyOn(context.logger, "error").mockReturnThis();
4419

4520
// act
4621
optimisticLockErrorFilter.catch(exception, context);
4722

48-
verify(mockedLogger.error(objectContaining({exception}))).once();
49-
verify(spiedResponse.status(409)).once();
23+
expect(context.logger.error).toHaveBeenCalledWith({
24+
event: "MIKRO_ORM_OPTIMISTIC_LOCK_ERROR",
25+
error_name: exception.name,
26+
error_message: exception.message,
27+
stack: exception.stack
28+
});
29+
expect(context.response.getBody()).toEqual("Update refused. The resource has changed on the server. Please try again later");
30+
expect(context.response.statusCode).toEqual(409);
5031
});
5132
});
5233
});

packages/orm/mikro-orm/src/filters/OptimisticLockErrorFilter.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@ export class OptimisticLockErrorFilter implements ExceptionFilterMethods<Optimis
88
const {response, logger} = ctx;
99

1010
logger.error({
11-
exception
11+
event: "MIKRO_ORM_OPTIMISTIC_LOCK_ERROR",
12+
error_name: exception.name,
13+
error_message: exception.message,
14+
stack: exception.stack
1215
});
1316

1417
response.status(409).body(`Update refused. The resource has changed on the server. Please try again later`);

packages/platform/platform-http/src/common/domain/PlatformContext.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {DIContext, DIContextOptions} from "@tsed/di";
1+
import {$emit, DIContext, DIContextOptions} from "@tsed/di";
22
import {PlatformHandlerMetadata} from "@tsed/platform-router";
33
import {EndpointMetadata} from "@tsed/schema";
44
import {IncomingMessage, ServerResponse} from "http";
@@ -81,11 +81,11 @@ export class PlatformContext<
8181
}
8282

8383
start() {
84-
return this.emit("$onRequest", this);
84+
return $emit("$onRequest", this);
8585
}
8686

8787
async finish() {
88-
await Promise.all([this.emit("$onResponse", this), this.destroy()]);
88+
await Promise.all([$emit("$onResponse", this), this.destroy()]);
8989
this.#isFinished = true;
9090
}
9191

packages/platform/platform-http/src/common/services/PlatformHandler.spec.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {Injectable} from "@tsed/di";
1+
import {Injectable, runInContext} from "@tsed/di";
22
import {PlatformHandlerMetadata, PlatformHandlerType} from "@tsed/platform-router";
33
import {EndpointMetadata, Get, View} from "@tsed/schema";
44

@@ -86,7 +86,7 @@ describe("PlatformHandler", () => {
8686

8787
expect(result).toBeInstanceOf(Function);
8888

89-
await $ctx.runInContext(() => result($ctx));
89+
await runInContext($ctx, () => result($ctx));
9090

9191
expect($ctx.data).toEqual("hello");
9292
expect(testService.use).toHaveBeenCalledWith($ctx);

0 commit comments

Comments
 (0)