You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.1 KiB

import * as AnalyticUnit from '../models/analytic_unit_model';
import { createAnalyticUnitFromObject } from '../controllers/analytics_controller';
6 years ago
import * as Router from 'koa-router';
7 years ago
6 years ago
async function getStatus(ctx: Router.IRouterContext) {
7 years ago
try {
let analyticUnitId = ctx.request.query.id;
if(analyticUnitId === undefined) {
throw new Error('Cannot get status of undefined id');
}
let analyticUnit = await AnalyticUnit.findById(analyticUnitId);
ctx.response.body = {
status: analyticUnit.status
};
if(analyticUnit.status === AnalyticUnit.AnalyticUnitStatus.FAILED) {
ctx.response.body.errorMessage = analyticUnit.error;
}
7 years ago
} catch(e) {
console.error(e);
ctx.response.status = 404;
ctx.response.body = 'Can`t find anything';
7 years ago
}
}
async function getUnit(ctx: Router.IRouterContext) {
7 years ago
try {
let analyticUnitId = ctx.request.query.id;
7 years ago
if(analyticUnitId === undefined) {
6 years ago
throw new Error('No id param in query');
7 years ago
}
6 years ago
let analyticUnit = await AnalyticUnit.findById(analyticUnitId);
6 years ago
ctx.response.body = {
name: analyticUnit.name,
metric: analyticUnit.metric,
status: analyticUnit.status
};
6 years ago
7 years ago
} catch(e) {
console.error(e);
// TODO: better send 404 when we know than isn`t found
ctx.response.status = 500;
6 years ago
ctx.response.body = 'Can`t find anything';
7 years ago
}
}
async function createUnit(ctx: Router.IRouterContext) {
7 years ago
try {
let id = await createAnalyticUnitFromObject(ctx.request.body);
ctx.response.body = { id };
7 years ago
} catch(e) {
ctx.response.status = 500;
ctx.response.body = {
7 years ago
code: 500,
6 years ago
message: `Creation error: ${e.message}`
};
7 years ago
}
7 years ago
}
async function deleteUnit(ctx: Router.IRouterContext) {
7 years ago
try {
await AnalyticUnit.remove(ctx.request.query.id);
ctx.response.body = {
7 years ago
code: 200,
message: 'Success'
};
7 years ago
} catch(e) {
ctx.response.status = 500;
ctx.response.body = {
7 years ago
code: 500,
6 years ago
message: `Deletion error: ${e.message}`
};
7 years ago
}
}
export var router = new Router();
7 years ago
router.get('/', getUnit);
6 years ago
router.get('/status', getStatus);
router.post('/', createUnit);
router.delete('/', deleteUnit);