forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform-pattern.utils.ts
More file actions
43 lines (39 loc) · 1.32 KB
/
Copy pathtransform-pattern.utils.ts
File metadata and controls
43 lines (39 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import {
isObject,
isString,
isNumber,
} from '@nestjs/common/utils/shared.utils';
import { MsPattern } from '../interfaces';
/**
* Transforms the Pattern to Route.
* 1. If Pattern is a `string`, it will be returned as it is.
* 2. If Pattern is a `number`, it will be converted to `string`.
* 3. If Pattern is a `JSON` object, it will be transformed to Route. For that end,
* the function will sort properties of `JSON` Object and creates `route` string
* according to the following template:
* <key1>:<value1>/<key2>:<value2>/.../<keyN>:<valueN>
*
* @param {MsPattern} pattern - client pattern
* @returns string
*/
export function transformPatternToRoute(pattern: MsPattern): string {
if (isString(pattern) || isNumber(pattern)) {
return `${pattern}`;
}
if (!isObject(pattern)) {
return pattern;
}
const sortedKeys = Object.keys(pattern).sort((a, b) =>
('' + a).localeCompare(b),
);
// Creates the array of Pattern params from sorted keys and their corresponding values
const sortedPatternParams = sortedKeys.map(key => {
let partialRoute = `"${key}":`;
partialRoute += isString(pattern[key])
? `"${transformPatternToRoute(pattern[key])}"`
: transformPatternToRoute(pattern[key]);
return partialRoute;
});
const route = sortedPatternParams.join(',');
return `{${route}}`;
}