]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/decorators/cd-encode.ts
1c8dc15c5f03d6b18430a5cb4f1563dfd2402c79
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / shared / decorators / cd-encode.ts
1 import * as _ from 'lodash';
2
3 /**
4 * This decorator can be used in a class or method.
5 * It will encode all the string parameters of all the methods of a class
6 * or, if applied on a method, the specified method.
7 *
8 * @export
9 * @param {Function} [target=null]
10 * @returns {*}
11 */
12 export function cdEncode(...args: any[]): any {
13 switch (args.length) {
14 case 1:
15 return encodeClass.apply(undefined, args);
16 case 3:
17 return encodeMethod.apply(undefined, args);
18 default:
19 throw new Error();
20 }
21 }
22
23 /**
24 * This decorator can be used in parameters only.
25 * It will exclude the parameter from being encode.
26 * This should be used in parameters that are going
27 * to be sent in the request's body.
28 *
29 * @export
30 * @param {Object} target
31 * @param {string} propertyKey
32 * @param {number} index
33 */
34 export function cdEncodeNot(target: object, propertyKey: string, index: number) {
35 const metadataKey = `__ignore_${propertyKey}`;
36 if (Array.isArray(target[metadataKey])) {
37 target[metadataKey].push(index);
38 } else {
39 target[metadataKey] = [index];
40 }
41 }
42
43 function encodeClass(target: Function) {
44 for (const propertyName of Object.getOwnPropertyNames(target.prototype)) {
45 const descriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
46
47 const isMethod = descriptor.value instanceof Function;
48 const isConstructor = propertyName === 'constructor';
49 if (!isMethod || isConstructor) {
50 continue;
51 }
52
53 encodeMethod(target.prototype, propertyName, descriptor);
54 Object.defineProperty(target.prototype, propertyName, descriptor);
55 }
56 }
57
58 function encodeMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
59 if (descriptor === undefined) {
60 descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
61 }
62 const originalMethod = descriptor.value;
63
64 descriptor.value = function() {
65 const metadataKey = `__ignore_${propertyKey}`;
66 const indices: number[] = target[metadataKey] || [];
67 const args = [];
68
69 for (let i = 0; i < arguments.length; i++) {
70 if (_.isString(arguments[i]) && indices.indexOf(i) === -1) {
71 args[i] = encodeURIComponent(arguments[i]);
72 } else {
73 args[i] = arguments[i];
74 }
75 }
76
77 const result = originalMethod.apply(this, args);
78 return result;
79 };
80 }