megalodon
Version:
Fediverse API client for node.js and browser
67 lines (66 loc) • 2.23 kB
JavaScript
import { EventEmitter } from 'events';
export class Parser extends EventEmitter {
message;
constructor() {
super();
this.message = '';
}
parse(chunk) {
if (chunk === ':thump\n') {
this.emit('heartbeat', {});
return;
}
this.message += chunk;
chunk = this.message;
const size = chunk.length;
let start = 0;
let offset = 0;
let curr;
let next;
while (offset < size) {
curr = chunk[offset];
next = chunk[offset + 1];
if (curr === '\n' && next === '\n') {
const piece = chunk.slice(start, offset);
offset += 2;
start = offset;
if (!piece.length)
continue;
const root = piece.split('\n');
if (root.length !== 2)
continue;
const event = root[0].substr(7);
const data = root[1].substr(6);
let jsonObj = {};
try {
jsonObj = JSON.parse(data);
}
catch (err) {
if (event !== 'delete') {
this.emit('error', new Error(`Error parsing API reply: '${piece}', error message: '${err}'`));
continue;
}
}
switch (event) {
case 'update':
this.emit('update', jsonObj);
break;
case 'notification':
this.emit('notification', jsonObj);
break;
case 'conversation':
this.emit('conversation', jsonObj);
break;
case 'delete':
this.emit('delete', data);
break;
default:
this.emit('error', new Error(`Unknown event has received: ${event}`));
continue;
}
}
offset++;
}
this.message = chunk.slice(start, size);
}
}