ffffng/server/resources/taskResource.js

54 lines
1.4 KiB
JavaScript
Raw 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-04 14:58:11 +02:00
function toExternalTask(task, id) {
return {
2016-06-04 14:58:11 +02:00
id: id,
name: task.name,
schedule: task.schedule,
runningSince: task.runningSince && task.runningSince.unix(),
lastRunStarted: task.lastRunStarted && task.lastRunStarted.unix()
};
}
return {
getAll: function (req, res) {
var tasks = Scheduler.getTasks();
2016-06-04 14:58:11 +02:00
return Resources.success(res, _.map(tasks, toExternalTask));
},
run: function (req, res) {
var id = Strings.normalizeString(Resources.getData(req).id);
if (!isValidId(id)) {
return Resources.error(res, {data: 'Invalid task id.', type: ErrorTypes.badRequest});
}
var tasks = Scheduler.getTasks();
var task = tasks[id];
if (!task) {
return Resources.error(res, {data: 'Task not found.', type: ErrorTypes.notFound});
}
if (task.runningSince) {
return Resources.error(res, {data: 'Task already running.', type: ErrorTypes.conflict});
}
task.run();
2016-06-04 14:58:11 +02:00
return Resources.success(res, toExternalTask(task, id));
}
};
});