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.

80 lines
1.8 KiB

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