|
| 1 | +require('../lib/fakes'); |
| 2 | + |
| 3 | +module.exports = function upload(stream, idOrPath, tag, done) { |
| 4 | + var blob = blobManager.create(account); |
| 5 | + var tx = db.begin(); |
| 6 | + function backoff(err) { |
| 7 | + tx.rollback(); |
| 8 | + return done(err); |
| 9 | + } |
| 10 | + var intentionalErrorShouldBeTriggered = function(){ |
| 11 | + return LIKELIHOOD_OF_REJECTION && Math.random() <= LIKELIHOOD_OF_REJECTION; |
| 12 | + } |
| 13 | + |
| 14 | + blob.put(stream, function (err, blobId) { |
| 15 | + if (err) return done(err); |
| 16 | + self.byUuidOrPath(idOrPath).get(function (err, file) { |
| 17 | + if (err) return done(err); |
| 18 | + var previousId = file ? file.version : null; |
| 19 | + var version = { |
| 20 | + userAccountId: userAccount.id, |
| 21 | + date: new Date(), |
| 22 | + blobId: blobId, |
| 23 | + creatorId: userAccount.id, |
| 24 | + previousId: previousId, |
| 25 | + }; |
| 26 | + version.id = Version.createHash(version); |
| 27 | + Version.insert(version).execWithin(tx, function (err) { |
| 28 | + if (err) return backoff(err); |
| 29 | + if(intentionalErrorShouldBeTriggered()) return done(new Error("intentional failure")); |
| 30 | + if (!file) { |
| 31 | + var splitPath = idOrPath.split('/'); |
| 32 | + var fileName = splitPath[splitPath.length - 1]; |
| 33 | + var newId = uuid.v1(); |
| 34 | + self.createQuery(idOrPath, { |
| 35 | + id: newId, |
| 36 | + userAccountId: userAccount.id, |
| 37 | + name: fileName, |
| 38 | + version: version.id |
| 39 | + }, function (err, q) { |
| 40 | + if (err) return backoff(err); |
| 41 | + if(intentionalErrorShouldBeTriggered()) return done(new Error("intentional failure")); |
| 42 | + q.execWithin(tx, function (err) { |
| 43 | + afterFileExists(err, newId); |
| 44 | + }); |
| 45 | + |
| 46 | + }) |
| 47 | + } |
| 48 | + else return afterFileExists(null, file.id); |
| 49 | + }); |
| 50 | + function afterFileExists(err, fileId) { |
| 51 | + if (err) return backoff(err); |
| 52 | + if(intentionalErrorShouldBeTriggered()) return done(new Error("intentional failure")); |
| 53 | + FileVersion.insert({fileId: fileId,versionId: version.id}) |
| 54 | + .execWithin(tx, function (err) { |
| 55 | + if (err) return backoff(err); |
| 56 | + if(intentionalErrorShouldBeTriggered()) return done(new Error("intentional failure")); |
| 57 | + File.whereUpdate({id: fileId}, { |
| 58 | + version: version.id |
| 59 | + }).execWithin(tx, function (err) { |
| 60 | + if (err) return backoff(err); |
| 61 | + if(intentionalErrorShouldBeTriggered()) return done(new Error("intentional failure")); |
| 62 | + tx.commit(done); |
| 63 | + }); |
| 64 | + }) |
| 65 | + } |
| 66 | + }); |
| 67 | + }); |
| 68 | +} |
0 commit comments