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.

85 lines
2.1 KiB

6 years ago
import { getJsonDataSync, writeJsonDataSync } from '../services/json'
6 years ago
import { ANALYTIC_UNITS_PATH } from '../config'
6 years ago
6 years ago
import * as crypto from 'crypto';
6 years ago
import * as path from 'path'
import * as fs from 'fs'
6 years ago
export type Datasource = {
method: string,
data: Object,
params: Object,
type: string,
url: string
}
export type Metric = {
datasource: string,
targets: string[]
}
6 years ago
export type AnalyticUnitId = string;
6 years ago
export type AnalyticUnit = {
6 years ago
id?: AnalyticUnitId,
6 years ago
name: string,
panelUrl: string,
6 years ago
type: string,
6 years ago
metric: Metric,
datasource: Datasource
status: string,
error?: string,
lastPredictionTime: number,
nextId: number
}
6 years ago
export function createItem(item: AnalyticUnit): AnalyticUnitId {
6 years ago
const hashString = item.name + (new Date()).toString();
6 years ago
const newId: AnalyticUnitId = crypto.createHash('md5').update(hashString).digest('hex');
6 years ago
let filename = path.join(ANALYTIC_UNITS_PATH, `${newId}.json`);
6 years ago
if(fs.existsSync(filename)) {
6 years ago
throw new Error(`Can't create item with id ${newId}`);
6 years ago
}
6 years ago
save(newId, item);
6 years ago
item.id = newId;
6 years ago
return newId;
6 years ago
}
6 years ago
export function remove(id: AnalyticUnitId) {
6 years ago
let filename = path.join(ANALYTIC_UNITS_PATH, `${id}.json`);
6 years ago
fs.unlinkSync(filename);
}
6 years ago
export function save(id: AnalyticUnitId, unit: AnalyticUnit) {
let filename = path.join(ANALYTIC_UNITS_PATH, `${id}.json`);
return writeJsonDataSync(filename, unit);
6 years ago
}
6 years ago
// TODO: make async
6 years ago
export function findById(id: AnalyticUnitId): AnalyticUnit {
6 years ago
let filename = path.join(ANALYTIC_UNITS_PATH, `${id}.json`);
6 years ago
if(!fs.existsSync(filename)) {
6 years ago
throw new Error(`Can't find Analytic Unit with id ${id}`);
6 years ago
}
return getJsonDataSync(filename);
}
6 years ago
export function setStatus(predictorId: AnalyticUnitId, status: string, error?: string) {
let info = findById(predictorId);
6 years ago
info.status = status;
if(error !== undefined) {
info.error = error;
} else {
info.error = '';
}
6 years ago
save(predictorId, info);
6 years ago
}
6 years ago
export function setPredictionTime(id: AnalyticUnitId, time: number) {
6 years ago
let info = findById(id);
6 years ago
info.lastPredictionTime = time;
save(id, info);
6 years ago
}