1 import * as _ from 'lodash';
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.
9 * @param {Function} [target=null]
12 export function cdEncode(...args: any[]): any {
13 switch (args.length) {
15 return encodeClass.apply(undefined, args);
17 return encodeMethod.apply(undefined, args);
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.
30 * @param {Object} target
31 * @param {string} propertyKey
32 * @param {number} index
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);
39 target[metadataKey] = [index];
43 function encodeClass(target: Function) {
44 for (const propertyName of Object.getOwnPropertyNames(target.prototype)) {
45 const descriptor = Object.getOwnPropertyDescriptor(target.prototype, propertyName);
47 const isMethod = descriptor.value instanceof Function;
48 const isConstructor = propertyName === 'constructor';
49 if (!isMethod || isConstructor) {
53 encodeMethod(target.prototype, propertyName, descriptor);
54 Object.defineProperty(target.prototype, propertyName, descriptor);
58 function encodeMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
59 if (descriptor === undefined) {
60 descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
62 const originalMethod = descriptor.value;
64 descriptor.value = function() {
65 const metadataKey = `__ignore_${propertyKey}`;
66 const indices: number[] = target[metadataKey] || [];
69 for (let i = 0; i < arguments.length; i++) {
70 if (_.isString(arguments[i]) && indices.indexOf(i) === -1) {
71 args[i] = encodeURIComponent(arguments[i]);
73 args[i] = arguments[i];
77 const result = originalMethod.apply(this, args);