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.

108 lines
2.6 KiB

import { exporterFactory } from '../services/exporter.factory';
import { CSV_PATH } from '../config';
import { validateGrafanaUrl } from '../services/api_keys';
6 years ago
2 years ago
import { ExportTask } from '../types';
import * as express from 'express';
2 years ago
import * as _ from 'lodash';
import * as path from 'path';
import * as fs from 'fs';
6 years ago
type TRequest = {
body: {
2 years ago
task: ExportTask,
url: string,
timeZoneName: string,
},
};
6 years ago
async function getTasks(req, res) {
2 years ago
const resp: ExportTask[] = [];
fs.readdir(CSV_PATH, (err, items) => {
if(err) {
console.error(err);
2 years ago
res.status(500).send(err.message);
} else {
for(let item of items) {
let file = path.parse(item);
if(file.ext !== '.json') {
continue;
}
// TODO: read async
let data = fs.readFileSync(path.join(CSV_PATH, item), 'utf8');
try {
let status = JSON.parse(data);
resp.push(status);
} catch(e) {
console.log(`Cannot read file /exporter/${item}. if this error doesn't repeat, maybe the file is being updated at the moment`);
}
}
res.status(200).send(resp);
}
});
}
async function addTask(req: TRequest, res) {
const body = req.body;
const clientUrl = body.url;
2 years ago
if (_.isEmpty(clientUrl)) {
res.status(400).send('"url" field is required');
return;
2 years ago
}
const task = body.task;
if (_.isEmpty(task)) {
res.status(400).send('"task" field is required');
return;
}
try {
validateGrafanaUrl(clientUrl);
} catch(e) {
res.status(500).send(e.message);
return;
2 years ago
}
const datasourceUrl = `${new URL(clientUrl).origin}/api/ds/query`;
6 years ago
2 years ago
const from = +task.timeRange.from;
const to = +task.timeRange.to;
if (isNaN(from) || isNaN(to)) {
res.status(400).send('Range error: please fill both "from" and "to" fields');
return;
2 years ago
} else if (from >= to) {
res.status(400).send('Range error: "from" should be less than "to"');
return;
6 years ago
}
2 years ago
const exporter = exporterFactory.getExporter();
exporter.export(task, datasourceUrl, body.timeZoneName);
2 years ago
res.status(200).send(`Export process started`);
6 years ago
}
async function deleteTask(req, res) {
2 years ago
let taskId = req.body.taskId;
let csvFilePath = path.join(CSV_PATH, `${taskId}.csv`);
let jsonFilePath = path.join(CSV_PATH, `${taskId}.json`);
if(fs.existsSync(csvFilePath)) {
fs.unlink(csvFilePath, err => console.error(err));
}
if(fs.existsSync(jsonFilePath)) {
fs.unlink(jsonFilePath, err => console.error(err));
}
res.status(200).send({ status: 'OK' });
}
6 years ago
export const router = express.Router();
router.get('/', getTasks);
6 years ago
router.post('/', addTask);
router.delete('/', deleteTask);