Browse Source

148 koa usage fix (#4)

* Fix middleware && add bodyparser

* req, res -> ctx
pull/1/head
rozetko 7 years ago committed by Alexey Velikiy
parent
commit
6ea415b7b8
  1. 8
      server/src/index.ts
  2. 11
      server/src/routes/alerts.ts
  3. 76
      server/src/routes/anomalies.ts
  4. 20
      server/src/routes/segments.ts

8
server/src/index.ts

@ -1,5 +1,6 @@
import * as Koa from 'koa'; import * as Koa from 'koa';
import * as Router from 'koa-router'; import * as Router from 'koa-router';
import * as bodyParser from 'koa-bodyparser';
import { router as anomaliesRouter } from './routes/anomalies'; import { router as anomaliesRouter } from './routes/anomalies';
@ -13,10 +14,13 @@ checkDataFolders();
var app = new Koa(); var app = new Koa();
const PORT = process.env.HASTIC_PORT || 8000; const PORT = process.env.HASTIC_PORT || 8000;
app.use(async function(ctx) { app.use(bodyParser())
app.use(async function(ctx, next) {
ctx.set('Access-Control-Allow-Origin', '*'); ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
}); });
var rootRouter = new Router(); var rootRouter = new Router();
@ -24,7 +28,7 @@ rootRouter.use('/anomalies', anomaliesRouter.routes(), anomaliesRouter.allowedMe
rootRouter.use('/segments', segmentsRouter.routes(), segmentsRouter.allowedMethods()); rootRouter.use('/segments', segmentsRouter.routes(), segmentsRouter.allowedMethods());
rootRouter.use('/alerts', alertsRouter.routes(), alertsRouter.allowedMethods()); rootRouter.use('/alerts', alertsRouter.routes(), alertsRouter.allowedMethods());
rootRouter.get('/', async (ctx) => { rootRouter.get('/', async (ctx) => {
ctx.body = { status: 'OK' }; ctx.response.body = { status: 'OK' };
}); });
app app

11
server/src/routes/alerts.ts

@ -6,9 +6,9 @@ import * as Router from 'koa-router';
function getAlert(ctx: Router.IRouterContext) { function getAlert(ctx: Router.IRouterContext) {
let anomalyId: AnomalyId = ctx.request.body.query.anomaly_id; let anomalyId: AnomalyId = ctx.request.query.anomaly_id;
let anomaly = loadAnomalyById(anomalyId) let anomaly = loadAnomalyById(anomalyId)
if (anomaly == null) { if(anomaly == null) {
anomalyId = getAnomalyIdByName(anomalyId.toLowerCase()); anomalyId = getAnomalyIdByName(anomalyId.toLowerCase());
} }
@ -23,10 +23,10 @@ function getAlert(ctx: Router.IRouterContext) {
function changeAlert(ctx: Router.IRouterContext) { function changeAlert(ctx: Router.IRouterContext) {
let anomalyId: AnomalyId = ctx.request.body.anomaly_id; let anomalyId: AnomalyId = ctx.request.body.anomaly_id;
let enable: boolean = ctx.body.enable; let enable: boolean = ctx.request.body.enable;
let anomaly = loadAnomalyById(anomalyId) let anomaly = loadAnomalyById(anomalyId)
if (anomaly == null) { if(anomaly == null) {
anomalyId = getAnomalyIdByName(anomalyId.toLowerCase()); anomalyId = getAnomalyIdByName(anomalyId.toLowerCase());
} }
@ -39,7 +39,8 @@ function changeAlert(ctx: Router.IRouterContext) {
alertsAnomalies.splice(pos, 1); alertsAnomalies.splice(pos, 1);
saveAlertsAnomalies(alertsAnomalies); saveAlertsAnomalies(alertsAnomalies);
} }
ctx.response.body = { status: 'Ok' }; ctx.response.body = { status: 'OK' };
} }
export const router = new Router(); export const router = new Router();

76
server/src/routes/anomalies.ts

@ -10,9 +10,9 @@ import {
import { runLearning } from '../services/analytics' import { runLearning } from '../services/analytics'
import { saveTargets } from '../services/metrics'; import { saveTargets } from '../services/metrics';
async function sendAnomalyTypeStatus(req, res) { async function sendAnomalyTypeStatus(ctx: Router.IRouterContext) {
let id = req.query.id; let id = ctx.request.query.id;
let name = req.query.name; let name = ctx.request.query.name;
try { try {
let anomaly: Anomaly; let anomaly: Anomaly;
if(id !== undefined) { if(id !== undefined) {
@ -21,28 +21,26 @@ async function sendAnomalyTypeStatus(req, res) {
anomaly = loadAnomalyByName(name); anomaly = loadAnomalyByName(name);
} }
if(anomaly === null) { if(anomaly === null) {
res.status(404).send({ ctx.response.status = 404;
code: 404,
message: 'Not found'
});
return; return;
} }
if(anomaly.status === undefined) { if(anomaly.status === undefined) {
throw new Error('No status for ' + name); throw new Error('No status for ' + name);
} }
res.status(200).send({ status: anomaly.status, errorMessage: anomaly.error }); ctx.response.body = { status: anomaly.status, errorMessage: anomaly.error };
} catch(e) { } catch(e) {
console.error(e); console.error(e);
// TODO: better send 404 when we know than isn`t found // TODO: better send 404 when we know than isn`t found
res.status(500).send({ error: 'Can`t return anything' }); ctx.response.status = 500;
ctx.response.body = { error: 'Can`t return anything' };
} }
} }
async function getAnomaly(req, res) { async function getAnomaly(ctx: Router.IRouterContext) {
try { try {
let id = req.query.id; let id = ctx.request.query.id;
let name = req.query.name; let name = ctx.request.query.name;
let anomaly:Anomaly; let anomaly:Anomaly;
if(id !== undefined) { if(id !== undefined) {
@ -51,66 +49,65 @@ async function getAnomaly(req, res) {
anomaly = loadAnomalyByName(name.toLowerCase()); anomaly = loadAnomalyByName(name.toLowerCase());
} }
if(anomaly === null) { if(anomaly === null) {
res.status(404).send({ ctx.response.status = 404;
code: 404,
message: 'Not found'
});
return; return;
} }
let payload = JSON.stringify({ ctx.response.body = {
name: anomaly.name, name: anomaly.name,
metric: anomaly.metric, metric: anomaly.metric,
status: anomaly.status status: anomaly.status
}); };
res.status(200).send(payload)
} catch(e) { } catch(e) {
console.error(e); console.error(e);
// TODO: better send 404 when we know than isn`t found // TODO: better send 404 when we know than isn`t found
res.status(500).send('Can`t get anything'); ctx.response.status = 500;
ctx.response.body = 'Can`t get anything';
} }
} }
async function createAnomaly(req, res) { async function createAnomaly(ctx: Router.IRouterContext) {
try { try {
let body = ctx.request.body;
const metric:Metric = { const metric:Metric = {
datasource: req.body.metric.datasource, datasource: body.metric.datasource,
targets: saveTargets(req.body.metric.targets) targets: saveTargets(body.metric.targets)
}; };
const anomaly:Anomaly = { const anomaly:Anomaly = {
name: req.body.name, name: body.name,
panelUrl: req.body.panelUrl, panelUrl: body.panelUrl,
metric: metric, metric: metric,
datasource: req.body.datasource, datasource: body.datasource,
status: 'learning', status: 'learning',
last_prediction_time: 0, last_prediction_time: 0,
next_id: 0 next_id: 0
}; };
let anomalyId = insertAnomaly(anomaly); let anomalyId = insertAnomaly(anomaly);
if(anomalyId === null) { if(anomalyId === null) {
res.status(403).send({ ctx.response.status = 403;
ctx.response.body = {
code: 403, code: 403,
message: 'Already exists' message: 'Already exists'
}); };
} }
let payload = JSON.stringify({ anomaly_id: anomalyId }) ctx.response.body = { anomaly_id: anomalyId };
res.status(200).send(payload);
runLearning(anomalyId); runLearning(anomalyId);
} catch(e) { } catch(e) {
res.status(500).send({ ctx.response.status = 500;
ctx.response.body = {
code: 500, code: 500,
message: 'Internal error' message: 'Internal error'
}); };
} }
} }
function deleteAnomaly(req, res) { function deleteAnomaly(ctx: Router.IRouterContext) {
try { try {
let id = req.query.id; let id = ctx.request.query.id;
let name = req.query.name; let name = ctx.request.query.name;
if(id !== undefined) { if(id !== undefined) {
removeAnomaly(id); removeAnomaly(id);
@ -118,15 +115,16 @@ function deleteAnomaly(req, res) {
removeAnomaly(name.toLowerCase()); removeAnomaly(name.toLowerCase());
} }
res.status(200).send({ ctx.response.body = {
code: 200, code: 200,
message: 'Success' message: 'Success'
}); };
} catch(e) { } catch(e) {
res.status(500).send({ ctx.response.status = 500;
ctx.response.body = {
code: 500, code: 500,
message: 'Internal error' message: 'Internal error'
}); };
} }
} }

20
server/src/routes/segments.ts

@ -15,15 +15,15 @@ import { runLearning } from '../services/analytics';
async function sendSegments(ctx: Router.IRouterContext) { async function sendSegments(ctx: Router.IRouterContext) {
let anomalyId: AnomalyId = ctx.query.anomaly_id; let anomalyId: AnomalyId = ctx.request.query.anomaly_id;
let anomaly:Anomaly = loadAnomalyById(anomalyId); let anomaly:Anomaly = loadAnomalyById(anomalyId);
if(anomaly === null) { if(anomaly === null) {
anomalyId = getAnomalyIdByName(anomalyId); anomalyId = getAnomalyIdByName(anomalyId);
} }
let lastSegmentId = ctx.query.last_segment; let lastSegmentId = ctx.request.query.last_segment;
let timeFrom = ctx.query.from; let timeFrom = ctx.request.query.from;
let timeTo = ctx.query.to; let timeTo = ctx.request.query.to;
let segments = getLabeledSegments(anomalyId); let segments = getLabeledSegments(anomalyId);
@ -45,9 +45,9 @@ async function sendSegments(ctx: Router.IRouterContext) {
} }
async function updateSegments(req, res) { async function updateSegments(ctx: Router.IRouterContext) {
try { try {
let segmentsUpdate = req.body; let segmentsUpdate = ctx.request.body;
let anomalyId = segmentsUpdate.anomaly_id; let anomalyId = segmentsUpdate.anomaly_id;
let anomalyName = segmentsUpdate.name; let anomalyName = segmentsUpdate.name;
@ -59,15 +59,15 @@ async function updateSegments(req, res) {
let addedIds = insertSegments(anomalyId, segmentsUpdate.added_segments, true); let addedIds = insertSegments(anomalyId, segmentsUpdate.added_segments, true);
removeSegments(anomalyId, segmentsUpdate.removed_segments); removeSegments(anomalyId, segmentsUpdate.removed_segments);
let payload = JSON.stringify({ added_ids: addedIds }); ctx.response.body = { added_ids: addedIds };
res.status(200).send(payload);
runLearning(anomalyId); runLearning(anomalyId);
} catch(e) { } catch(e) {
res.status(500).send({ ctx.response.status = 500;
ctx.response.body = {
code: 500, code: 500,
message: 'Internal error' message: 'Internal error'
}); };
} }
} }

Loading…
Cancel
Save