ContentLine.ts 2 KB
Newer Older
Mark Stenglein's avatar
Mark Stenglein committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import { isAlpha } from "./util";

/**
 * Implementation of a Content Line from RFC 5545
 *
 * @author Mark Stenglein <mark@stengle.in>
 *
 * Chapter 3.1 defines the content line. This implementation will use it as an
 * abstract class which can be extended later by the specific content types.
 *
 * This class defines all of the general features specified by the chapter,
 * while leaving the specific features required by individual component objects
 * unfilled.
 */
15
export default class ContentLine {
Mark Stenglein's avatar
Mark Stenglein committed
16
    private _name: string;
17
    private _params: string[] = [];
Mark Stenglein's avatar
Mark Stenglein committed
18 19
    private _value: string;

20
    constructor(inName: string, inParams: string[], inValue: string) {
Mark Stenglein's avatar
Mark Stenglein committed
21
        this.name = inName;
22
        this._params = inParams;
Mark Stenglein's avatar
Mark Stenglein committed
23 24 25 26 27 28 29 30 31
        this.value = inValue;
    }

    /* Getters */

    get name(): string {
        return this._name;
    }

32 33
    get params(): string[] {
        return this._params;
Mark Stenglein's avatar
Mark Stenglein committed
34 35 36 37 38 39 40 41 42 43 44 45 46
    }

    get value(): string {
        return this._value;
    }

    /* Setters */

    set name(newName: string) {
        if (isAlpha(newName)) {
            this._name = newName;
        }
        else {
47
            throw new TypeError("'name' must be alphabetic!");
Mark Stenglein's avatar
Mark Stenglein committed
48 49 50 51 52 53 54 55
        }
    }

    set value(newValue: string) {
        if (isAlpha(newValue)) {
            this._value = newValue;
        }
    }
56 57 58

    /**
     * Folds lines into 74 octet sections
Mark Stenglein's avatar
Mark Stenglein committed
59
     *
60
     * @author Sebastian Pekarek <mail@sebbo.net>
Mark Stenglein's avatar
Mark Stenglein committed
61
     *
62 63 64
     * TODO: Make sure that this handles multi-octed UTF-8 segments properly.
     */
    static fold(line: string): string {
65
        return line.match(/(.{1,74})/g).join("\r\n ");
66 67 68 69
    }

    /**
     * Generates a folded content line to use to create the final file.
Mark Stenglein's avatar
Mark Stenglein committed
70
     *
71 72 73 74 75
     * @author Mark Stenglein <mark@stengle.in>
     */
    public generate(): string {
        let outputLine = this.name;

76
        this.params.forEach((param) => {
77
            outputLine += ";";
78 79 80
            outputLine += param;
        });

81
        outputLine += ":" + this.value + "\r\n";
82 83 84

        return ContentLine.fold(outputLine);
    }
85
}