mirror of
https://github.com/nestjs/nest.git
synced 2026-10-28 09:45:43 +08:00
perf(microservices): parse message patterns only when they may be json (#18277)
This commit is contained in:
1 parent
ff84deb156
commit
11e1466b96
2 files changed
+55
-1
No files matched your search
@@ -54,6 +54,10 @@ import { MESSAGES } from '@nestjs/core/internal';
|
||||
|
||||
const MAX_PACKET_ID_LENGTH = 256;
|
||||
|
||||
// Matches every text JSON.parse() accepts. A string pattern it does not match
|
||||
// (e.g. "user.created") is used as it is, as parsing it would only throw.
|
||||
const JSON_TEXT = /^\s*(?:[{["\-\d]|(?:true|false|null)\s*$)/;
|
||||
|
||||
/**
|
||||
* @publicApi
|
||||
*/
|
||||
@@ -461,7 +465,7 @@ export abstract class Server<
|
||||
let validPattern: MsPattern;
|
||||
|
||||
try {
|
||||
validPattern = JSON.parse(pattern);
|
||||
validPattern = JSON_TEXT.test(pattern) ? JSON.parse(pattern) : pattern;
|
||||
} catch (error) {
|
||||
// Uses a fundamental object (`pattern` variable without any conversion)
|
||||
validPattern = pattern;
|
||||
|
||||
@@ -115,6 +115,56 @@ describe('Server', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe(`when gets a 'string' pattern that is not 'json'`, () => {
|
||||
it(`should not parse it`, () => {
|
||||
const parseSpy = vi.spyOn(JSON, 'parse');
|
||||
untypedServer.getRouteFromPattern('user.created');
|
||||
untypedServer.getRouteFromPattern('notify');
|
||||
untypedServer.getRouteFromPattern(' trueish');
|
||||
|
||||
expect(parseSpy).not.toHaveBeenCalled();
|
||||
expect(normalizePatternStub.mock.calls.map(([arg]) => arg)).toEqual([
|
||||
'user.created',
|
||||
'notify',
|
||||
' trueish',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe(`when gets a 'string' pattern that may be 'json'`, () => {
|
||||
it(`should call 'transformPatternToRoute' with what 'JSON.parse' returns`, () => {
|
||||
const patterns = [
|
||||
'42',
|
||||
'-1',
|
||||
' true ',
|
||||
'false',
|
||||
'null',
|
||||
'"hello"',
|
||||
'[1]',
|
||||
];
|
||||
patterns.forEach(item => untypedServer.getRouteFromPattern(item));
|
||||
|
||||
expect(normalizePatternStub.mock.calls.map(([arg]) => arg)).toEqual([
|
||||
42,
|
||||
-1,
|
||||
true,
|
||||
false,
|
||||
null,
|
||||
'hello',
|
||||
[1],
|
||||
]);
|
||||
});
|
||||
|
||||
it(`should call 'transformPatternToRoute' with the 'string' argument when it is not 'json'`, () => {
|
||||
const patterns = ['2fa.verify', '{"cmd":', '"hello', 'null.created'];
|
||||
patterns.forEach(item => untypedServer.getRouteFromPattern(item));
|
||||
|
||||
expect(normalizePatternStub.mock.calls.map(([arg]) => arg)).toEqual(
|
||||
patterns,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('send', () => {
|
||||
|
||||
Reference in new issue
Block a user