Code coverage report for core/src/log/message-template.ts

Statements: 50% (8 / 16)      Branches: 100% (1 / 1)      Functions: 50% (2 / 4)      Lines: 50% (8 / 16)      Ignored: none     

All files » core/src/log/ » message-template.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                  1                             1       1             22 22 22                                           1 22    
import {MessageContext} from './message';
 
/**
 * Allows additional context to be added to the message string.
 */
export interface MessageTemplate {
  /**
   * Make a string given the `context`.
   * @param context
   *
   */
  format(context: MessageContext): string;
}
 
/**
 * Adds no additonal context to the message string.
 */
export const rawMessageTemplate: MessageTemplate = {
  /**
   *
   * @param context
   * @returns context.message
   */
  format(context: MessageContext): string {
    return context.message;
  }
};
 
 
/**
 * Format a message using a lazily evaluated template string.
 */
export class TemplateStringMessageTemplate implements MessageTemplate {
  /**
   * Will render logger's fqn and the message.
   */
  static readonly DEFAULT_TEMPLATE = '${ctx.data.fqn || ""}: ${ctx.message || ""}';
  private readonly fmt: Function;
 
  /**
   *
   * @param template a template string. **Backticks are not necessary.**
   */
  constructor(readonly template = TemplateStringMessageTemplate.DEFAULT_TEMPLATE) {
    try {
      this.fmt = new Function('ctx', `return \`${this.template}\`;`);
    } catch (error) {
      console.error('TemplateStringMessageTemplate: Error creating template from `%s`!', this.template, error);
      throw error;
    }
  }
 
 
  format(context: MessageContext): string {
    let result: string;
    try {
      result = this.fmt(context);
    } catch (error) {
      console.error('TemplateStringMessageTemplate: Error formatting %o with template %s', context, this.template, error);
      result = context.message;
    }
    return result;
  }
 
}
 
 
export function templateString(template?: string): MessageTemplate {
  return new TemplateStringMessageTemplate(template);
}