Guest User

Untitled

a guest
May 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. interface PipedObject {
  2. property: string;
  3. pipe: PipeDefinition;
  4. }
  5.  
  6. interface PipeDefinition {
  7. name: string;
  8. params: string[];
  9. }
  10.  
  11. export class CustomTranslateCompiler implements TranslateCompiler {
  12.  
  13. constructor(private injector: Injector, private errorHandler: ErrorHandler) {
  14. }
  15.  
  16. public compile(value: string, lang: string): string | Function {
  17. return this.compileValue(value);
  18. }
  19.  
  20. public compileTranslations(translations: any, lang: string): any {
  21. this.iterateTranslations(translations);
  22. return translations;
  23. }
  24.  
  25. private iterateTranslations(obj) {
  26. for (let key in obj) {
  27. if (obj.hasOwnProperty(key)) {
  28. const val = obj[key];
  29. const isString = typeof val === 'string';
  30. if(key[0] === '@' && isString) {
  31. obj[key] = this.compileValue(val);
  32. } else if(!isString) {
  33. this.iterateTranslations(val);
  34. }
  35. }
  36. }
  37. }
  38.  
  39. private compileValue(val): Function {
  40. let parsedTranslation = this.parseTranslation(val);
  41. return (argsObj: object) => {
  42. let res = val;
  43. parsedTranslation.pipedObjects.forEach((o, i) => {
  44. const pipe = this.injector.get(o.pipe.name);
  45. const pipeParams = this.assignPipeParams(argsObj, o.pipe.params || []);
  46. const property = argsObj[o.property];
  47. if(!property) {
  48. this.errorHandler.handleError(
  49. new Error(`Object property: ${o.property} not found`)
  50. );
  51. }
  52. let pipedValue = pipe.transform(
  53. property,
  54. pipeParams.length === 1 ? pipeParams[0] : pipeParams
  55. );
  56. res = res.replace(parsedTranslation.matches[i], pipedValue);
  57. });
  58. return res;
  59. };
  60. }
  61.  
  62. private assignPipeParams(obj: object, params: string[]) {
  63. let assignedParams = [];
  64. params.forEach(p => {
  65. if(obj.hasOwnProperty(p)) {
  66. assignedParams.push(obj[p]);
  67. } else {
  68. assignedParams.push(p);
  69. }
  70. });
  71. return assignedParams;
  72. }
  73.  
  74. private parseTranslation(res: string): {pipedObjects: PipedObject[], matches: string[]} {
  75. let matches = res.match(/{{.[^{{]*}}/g);
  76. let pipedObjects: PipedObject[] = [];
  77. (matches || []).forEach((v) => {
  78. v = v.replace(/[{}\s]+/g, '');
  79. let pipes = v.split('|');
  80. let objectPropertyName = pipes[0];
  81. pipes = pipes.slice(1);
  82. for(let pipe of pipes) {
  83. let pipeTokens = pipe.split(':');
  84. pipedObjects.push({
  85. property: objectPropertyName,
  86. pipe: {
  87. name: pipeTokens[0],
  88. params: pipeTokens.slice(1)
  89. }
  90. });
  91. }
  92. });
  93. return {pipedObjects, matches};
  94. }
  95. }
Add Comment
Please, Sign In to add comment