line-parse.js 978 Bytes
const qs = require('querystring');
const crypto = global.yoho.crypto;
const logger = global.yoho.logger;

class Message {
    constructor(measurement, tags, fields, time) {
        this.measurement = measurement;
        this.tags = tags;
        this.fields = fields;
        this.time = time;
    }
}

const opt = {
    decodeURIComponent: decodeURIComponent
};

function parseMessage(line) {
    let measurement = line.split(',', 1)[0];
    let body = line.substring(measurement.length + 1);
    let tokens = body.split(' ');

    let [tags, fields, time] = [qs.parse(tokens[0], ',', '=', opt), qs.parse(tokens[1], ',', '=', opt), tokens[2]];

    return new Message(measurement, tags, fields, time);
}

function parse(data) {
    data = data.replace(/\"([^\"]*)\"/g, (match) => {
        return encodeURIComponent(match);
    });

    let lines = (data || '').split('\n');
    let messages = lines.map(parseMessage);

    return messages;
}

module.exports = {
    parse
};