Refactor local_loki_server

pull/208/head
Mikunj 7 years ago
parent 4a037387e9
commit 429bdd6460

@ -1,6 +1,14 @@
const http = require('http'); const http = require('http');
const EventEmitter = require('events'); const EventEmitter = require('events');
const STATUS = {
OK: 200,
BAD_REQUEST: 400,
NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
INTERNAL_SERVER_ERROR: 500,
};
class LocalLokiServer extends EventEmitter { class LocalLokiServer extends EventEmitter {
/** /**
* Creates an instance of LocalLokiServer. * Creates an instance of LocalLokiServer.
@ -11,47 +19,54 @@ class LocalLokiServer extends EventEmitter {
this.server = http.createServer((req, res) => { this.server = http.createServer((req, res) => {
let body = []; let body = [];
const sendResponse = (statusCode, message = null) => {
const headers = message && {
'Content-Type': 'text/plain',
};
res.writeHead(statusCode, headers);
res.end(message);
};
if (req.method !== 'POST') {
sendResponse(STATUS.METHOD_NOT_ALLOWED);
return;
}
// Check endpoints // Check endpoints
if (req.method === 'POST') { req
req .on('error', () => {
.on('error', () => { // Internal server error
// Internal server error sendResponse(STATUS.INTERNAL_SERVER_ERROR);
res.statusCode = 500; })
res.end(); .on('data', chunk => {
}) body.push(chunk);
.on('data', chunk => { })
body.push(chunk); .on('end', () => {
}) try {
.on('end', () => { body = Buffer.concat(body).toString();
try { } catch (e) {
body = Buffer.concat(body).toString(); // Internal server error: failed to convert body to string
} catch (e) { sendResponse(STATUS.INTERNAL_SERVER_ERROR);
// Error occurred while converting to string }
res.statusCode = 500;
res.end();
}
// Check endpoints here // Check endpoints here
if (req.url === '/v1/storage_rpc') { if (req.url === '/v1/storage_rpc') {
try {
const bodyObject = JSON.parse(body); const bodyObject = JSON.parse(body);
if (bodyObject.method !== 'store') { if (bodyObject.method !== 'store') {
res.writeHead(404, { 'Content-Type': 'text/plain' }); sendResponse(STATUS.NOT_FOUND, 'Invalid endpoint!');
res.end('Invalid endpoint!');
return; return;
} }
this.emit('message', bodyObject.params.data); this.emit('message', bodyObject.params.data);
res.statusCode = 200; sendResponse(STATUS.OK);
res.end(); } catch (e) {
} else { // Bad Request: Failed to decode json
res.writeHead(404, { 'Content-Type': 'text/plain' }); sendResponse(STATUS.BAD_REQUEST, 'Failed to decode JSON');
res.end('Invalid endpoint!');
} }
}); } else {
} else { sendResponse(STATUS.NOT_FOUND, 'Invalid endpoint!');
// Method Not Allowed }
res.statusCode = 405; });
res.end();
}
}); });
} }

Loading…
Cancel
Save