Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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};
- }
- }
Add Comment
Please, Sign In to add comment