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.
 
 
 

107 lines
2.6 KiB

import { exporterFactory } from '../services/exporter.factory';
import { CSV_PATH } from '../config';
import { validateGrafanaUrl } from '../services/api_keys';
import { ExportTask } from '../types';
import * as express from 'express';
import * as _ from 'lodash';
import * as path from 'path';
import * as fs from 'fs';
type TRequest = {
body: {
task: ExportTask,
url: string,
timeZoneName: string,
},
};
async function getTasks(req, res) {
const resp: ExportTask[] = [];
fs.readdir(CSV_PATH, (err, items) => {
if(err) {
console.error(err);
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;
if (_.isEmpty(clientUrl)) {
res.status(400).send('"url" field is required');
return;
}
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;
}
const datasourceUrl = `${new URL(clientUrl).origin}/api/ds/query`;
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;
} else if (from >= to) {
res.status(400).send('Range error: "from" should be less than "to"');
return;
}
const exporter = exporterFactory.getExporter();
exporter.export(task, datasourceUrl, body.timeZoneName);
res.status(200).send(`Export process started`);
}
async function deleteTask(req, res) {
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' });
}
export const router = express.Router();
router.get('/', getTasks);
router.post('/', addTask);
router.delete('/', deleteTask);