ffffng/server/resources/taskResource.js

128 lines
3.5 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
angular.module('ffffng').factory('TaskResource', function (
Constraints,
Validator,
_,
Strings,
Resources,
ErrorTypes,
Scheduler
) {
var isValidId = Validator.forConstraint(Constraints.id);
2016-06-07 11:01:35 +02:00
function toExternalTask(task) {
return {
2016-06-07 11:01:35 +02:00
id: task.id,
name: task.name,
2016-06-21 14:55:02 +02:00
description: task.description,
schedule: task.schedule,
runningSince: task.runningSince && task.runningSince.unix(),
lastRunStarted: task.lastRunStarted && task.lastRunStarted.unix(),
lastRunDuration: task.lastRunDuration || undefined,
state: task.state,
enabled: task.enabled
};
}
function withValidTaskId(req, res, callback) {
var id = Strings.normalizeString(Resources.getData(req).id);
if (!isValidId(id)) {
return callback({data: 'Invalid task id.', type: ErrorTypes.badRequest});
}
callback(null, id);
}
function getTask(id, callback) {
var tasks = Scheduler.getTasks();
var task = tasks[id];
if (!task) {
return callback({data: 'Task not found.', type: ErrorTypes.notFound});
}
callback(null, task);
}
function withTask(req, res, callback) {
withValidTaskId(req, res, function (err, id) {
if (err) {
return callback(err);
}
getTask(id, function (err, task) {
if (err) {
return callback(err);
}
2016-06-07 11:01:35 +02:00
callback(null, task);
});
});
}
function setTaskEnabled(req, res, enable) {
2016-06-07 11:01:35 +02:00
withTask(req, res, function (err, task) {
if (err) {
return Resources.error(res, err);
}
task.enabled = !!enable; // ensure boolean
2016-06-07 11:01:35 +02:00
return Resources.success(res, toExternalTask(task));
});
}
return {
getAll: function (req, res) {
2016-07-23 11:30:41 +02:00
Resources.getValidRestParams('list', null, req, function (err, restParams) {
2016-06-07 11:01:35 +02:00
if (err) {
return Resources.error(res, err);
}
var tasks = Resources.sort(
_.values(Scheduler.getTasks()),
['id', 'name', 'schedule', 'state', 'runningSince', 'lastRunStarted'],
restParams
);
2016-06-07 12:45:23 +02:00
var filteredTasks = Resources.filter(
tasks,
['id', 'name', 'schedule', 'state'],
restParams
);
var total = filteredTasks.length;
2016-06-07 11:01:35 +02:00
2016-06-07 12:45:23 +02:00
var pageTasks = Resources.getPageEntities(filteredTasks, restParams);
2016-06-07 11:01:35 +02:00
res.set('X-Total-Count', total);
return Resources.success(res, _.map(pageTasks, toExternalTask));
});
},
run: function (req, res) {
2016-06-07 11:01:35 +02:00
withTask(req, res, function (err, task) {
if (err) {
return Resources.error(res, err);
}
if (task.runningSince) {
return Resources.error(res, {data: 'Task already running.', type: ErrorTypes.conflict});
}
task.run();
2016-06-07 11:01:35 +02:00
return Resources.success(res, toExternalTask(task));
});
},
enable: function (req, res) {
setTaskEnabled(req, res, true);
},
disable: function (req, res) {
setTaskEnabled(req, res, false);
}
};
});