From 4df023f2d4e4ea93d3fbc6010f0460511ba45140 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Sun, 15 Jan 2017 19:53:11 +0100 Subject: Server: create transaction refractoring --- server/helpers/database-utils.js | 55 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 server/helpers/database-utils.js (limited to 'server/helpers/database-utils.js') diff --git a/server/helpers/database-utils.js b/server/helpers/database-utils.js new file mode 100644 index 000000000..046717517 --- /dev/null +++ b/server/helpers/database-utils.js @@ -0,0 +1,55 @@ +'use strict' + +const retry = require('async/retry') + +const db = require('../initializers/database') +const logger = require('./logger') + +const utils = { + retryTransactionWrapper, + transactionRetryer, + startSerializableTransaction +} + +// { arguments, errorMessage } +function retryTransactionWrapper (functionToRetry, options, finalCallback) { + const args = options.arguments ? options.arguments : [] + + utils.transactionRetryer( + function (callback) { + return functionToRetry.apply(this, args.concat([ callback ])) + }, + function (err) { + if (err) { + logger.error(options.errorMessage, { error: err }) + } + + // Do not return the error, continue the process + return finalCallback(null) + } + ) +} + +function transactionRetryer (func, callback) { + retry({ + times: 5, + + errorFilter: function (err) { + const willRetry = (err.name === 'SequelizeDatabaseError') + logger.debug('Maybe retrying the transaction function.', { willRetry }) + return willRetry + } + }, func, callback) +} + +function startSerializableTransaction (callback) { + console.log(db) + db.sequelize.transaction({ isolationLevel: 'SERIALIZABLE' }).asCallback(function (err, t) { + // We force to return only two parameters + return callback(err, t) + }) +} + +// --------------------------------------------------------------------------- + +module.exports = utils -- cgit v1.2.3