File tree Expand file tree Collapse file tree
packages/microservices/utils Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { isString , isObject } from '@nestjs/common/utils/shared.utils' ;
2+
3+ export class MsvcUtil {
4+
5+ /**
6+ * Transforms the Pattern to Route.
7+ * 1. If Pattern is a `string`, it will be returned as it is.
8+ * 2. If Pattern is a `JSON` object, it will be transformed to Route. For that end,
9+ * the function will sort properties of `JSON` Object and creates `route` string
10+ * according to the following template:
11+ * <key1>:<value1>/<key2>:<value2>/.../<keyN>:<valueN>
12+ *
13+ * @param {any } pattern - client pattern
14+ * @returns string
15+ */
16+ public static transformPatternToRoute ( pattern : any ) : string {
17+ // Returns the pattern according to the 1st
18+ if ( isString ( pattern ) ) {
19+ return pattern ;
20+ }
21+
22+ // Throws the error if the pattern has an incorrect type
23+ if ( ! isObject ( pattern ) ) {
24+ throw new Error ( `The pattern must be of type 'string' or 'object'!` ) ;
25+ }
26+
27+ // Gets keys of the JSON Pattern and sorts them
28+ const sortedKeys = Object . keys ( pattern )
29+ . sort ( ( a , b ) => ( '' + a ) . localeCompare ( b ) ) ;
30+
31+ // Creates the array of Pattern params from sorted keys and their corresponding values
32+ const sortedPatternParams = sortedKeys . map ( ( key ) =>
33+ `${ key } :${ pattern [ key ] } ` ) ;
34+
35+ // Creates and returns the Route
36+ const sortedPattern = sortedPatternParams . join ( '/' ) ;
37+ return sortedPattern ;
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments