/
promises-ecmascript6-native.js
67 lines (63 loc) · 1.97 KB
/
promises-ecmascript6-native.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
global.useNative = true;
try {
if (Promise.race.toString() !== 'function race() { [native code] }')
throw 0;
} catch (e) {
throw new Error("No ES6 promises available");
}
require('../lib/fakesP');
module.exports = function upload(stream, idOrPath, tag, done) {
var blob = blobManager.create(account);
var tx = db.begin();
var blobIdP = blob.put(stream);
var fileP = self.byUuidOrPath(idOrPath).get();
var version, fileId, file;
Promise.all([blobIdP, fileP]).then(function(result) {
var blobId = result[0];
var fileV = result[1];
file = fileV;
var previousId = file ? file.version : null;
version = {
userAccountId: userAccount.id,
date: new Date(),
blobId: blobId,
creatorId: userAccount.id,
previousId: previousId,
};
version.id = Version.createHash(version);
return Version.insert(version).execWithin(tx);
}).then(function() {
if (!file) {
var splitPath = idOrPath.split('/');
var fileName = splitPath[splitPath.length - 1];
var newId = uuid.v1();
return self.createQuery(idOrPath, {
id: newId,
userAccountId: userAccount.id,
name: fileName,
version: version.id
}).then(function(q) {
return q.execWithin(tx);
}).then(function() {
return newId;
});
} else {
return file.id;
}
}).then(function(fileIdV) {
fileId = fileIdV;
return FileVersion.insert({
fileId: fileId,
versionId: version.id
}).execWithin(tx);
}).then(function() {
return File.whereUpdate({id: fileId}, {version: version.id})
.execWithin(tx);
}).then(function() {
tx.commit();
return done();
}, function(err) {
tx.rollback();
return done(err);
});
}