line-parse.js 1.43 KB
const qs = require('querystring');
const routeDecode = require('../middleware/route-decode');

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

function parseMessage(line) {
    let measurement = line.split(',', 1)[0];
    let body = line.substring(measurement.length + 1);
    let tokens = body.split(' ');
    let fieldsStr = tokens.filter((t, i) => i > 0 && i < tokens.length - 1).join(' ');

    const tags = qs.parse(tokens[0], ',', '=');
    const time = tokens[tokens.length - 1];
    const fields = qs.parse(fieldsStr.replace(/,(\w+)=/g, '_$_$1='), '_$_', '=');

    // 服务器路由
    if (tags.path) {
        let [, p] = tags.path.split(']');

        p = routeDecode(p) || 'null';

        tags.path = p;
        tags.route = p;
    }

    if (fields.uid && fields.uid === '"undefined"') {
        fields.uid = '0';
    }

    // 具体请求路径
    if (tags.url) {
        try {
            tags.url = decodeURIComponent(tags.url);
        } catch (e) {}
    }

    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
};