You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.0 KiB
JavaScript
48 lines
1.0 KiB
JavaScript
"use strict";
|
|
|
|
const Promise = require("bluebird");
|
|
const { UniqueViolationError } = require("objection");
|
|
|
|
const pipe = require("@promistream/pipe");
|
|
const map = require("@promistream/map");
|
|
const mapFilter = require("@promistream/map-filter");
|
|
|
|
module.exports = function ({ db, knex }) {
|
|
return function processTaskSafely(task, processHandler) {
|
|
let lockStream = mapFilter((item) => {
|
|
return Promise.try(() => {
|
|
return db.TaskInProgress.query(knex).insert({
|
|
task: task,
|
|
item_id: item.id
|
|
});
|
|
}).then(() => {
|
|
return item;
|
|
}).catch(UniqueViolationError, () => {
|
|
return mapFilter.NoValue;
|
|
});
|
|
});
|
|
|
|
let processUnlockStream = map((item) => {
|
|
return Promise.try(() => {
|
|
return knex.transaction((tx) => {
|
|
return processHandler(item, tx);
|
|
});
|
|
}).finally(() => {
|
|
return db.TaskInProgress.query(knex)
|
|
.delete()
|
|
.where({
|
|
task: task,
|
|
item_id: item.id
|
|
});
|
|
}).then(() => {
|
|
return item;
|
|
});
|
|
});
|
|
|
|
return pipe([
|
|
lockStream,
|
|
processUnlockStream
|
|
]);
|
|
};
|
|
};
|