Created
May 16, 2018 20:56
-
-
Save CapLonelyFlaw/7cab4642806e86e72cbfafd82c3bcf76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PipedObject { | |
property: string; | |
pipe: PipeDefinition; | |
} | |
interface PipeDefinition { | |
name: string; | |
params: string[]; | |
} | |
export class CustomTranslateCompiler implements TranslateCompiler { | |
constructor(private injector: Injector, private errorHandler: ErrorHandler) { | |
} | |
public compile(value: string, lang: string): string | Function { | |
return this.compileValue(value); | |
} | |
public compileTranslations(translations: any, lang: string): any { | |
this.iterateTranslations(translations); | |
return translations; | |
} | |
private iterateTranslations(obj) { | |
for (let key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
const val = obj[key]; | |
const isString = typeof val === 'string'; | |
if(key[0] === '@' && isString) { | |
obj[key] = this.compileValue(val); | |
} else if(!isString) { | |
this.iterateTranslations(val); | |
} | |
} | |
} | |
} | |
private compileValue(val): Function { | |
let parsedTranslation = this.parseTranslation(val); | |
return (argsObj: object) => { | |
let res = val; | |
parsedTranslation.pipedObjects.forEach((o, i) => { | |
const pipe = this.injector.get(o.pipe.name); | |
const pipeParams = this.assignPipeParams(argsObj, o.pipe.params || []); | |
const property = argsObj[o.property]; | |
if(!property) { | |
this.errorHandler.handleError( | |
new Error(`Object property: ${o.property} not found`) | |
); | |
} | |
let pipedValue = pipe.transform( | |
property, | |
pipeParams.length === 1 ? pipeParams[0] : pipeParams | |
); | |
res = res.replace(parsedTranslation.matches[i], pipedValue); | |
}); | |
return res; | |
}; | |
} | |
private assignPipeParams(obj: object, params: string[]) { | |
let assignedParams = []; | |
params.forEach(p => { | |
if(obj.hasOwnProperty(p)) { | |
assignedParams.push(obj[p]); | |
} else { | |
assignedParams.push(p); | |
} | |
}); | |
return assignedParams; | |
} | |
private parseTranslation(res: string): {pipedObjects: PipedObject[], matches: string[]} { | |
let matches = res.match(/{{.[^{{]*}}/g); | |
let pipedObjects: PipedObject[] = []; | |
(matches || []).forEach((v) => { | |
v = v.replace(/[{}\s]+/g, ''); | |
let pipes = v.split('|'); | |
let objectPropertyName = pipes[0]; | |
pipes = pipes.slice(1); | |
for(let pipe of pipes) { | |
let pipeTokens = pipe.split(':'); | |
pipedObjects.push({ | |
property: objectPropertyName, | |
pipe: { | |
name: pipeTokens[0], | |
params: pipeTokens.slice(1) | |
} | |
}); | |
} | |
}); | |
return {pipedObjects, matches}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment