-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (66 loc) · 2.2 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
'use strict';
var async = require('async');
var crypto = require('crypto');
var Anyfetch = require('anyfetch');
var JSONc14n = require('./helpers/JSONc14n.js');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} original document
* @param {object} changes object provided by anyFetch's API. Update this object to send document's modification to anyFetch's API.
* @param {function} cb Callback, first parameter is the error if any, then the processed data
*/
module.exports = function(path, document, changes, cb) {
var anyfetch = new Anyfetch(document.access_token);
anyfetch.setApiUrl(cb.apiUrl);
var haveChanges = true;
async.waterfall([
function generateHash(cb) {
var shasum = crypto.createHash('sha1');
delete document.metadata.hash;
shasum.update(JSONc14n.stringify(document.metadata));
cb(null, shasum.digest('hex'));
},
function getDocumentsWithSameHash(hash, cb) {
changes.metadata = {
hash: hash
};
anyfetch.getDocuments({'@hash': hash, 'fields': 'data'}, cb);
},
function deleteOldDocuments(res, cb) {
var documents = res.body.data;
var containsDocument = documents.some(function(current) {
return current.id === document.id;
});
if(!containsDocument) {
documents.push(document);
}
var mostRecentDocument = documents.reduce(function(previousDoc, currentDoc) {
if(new Date(previousDoc.modification_date) > new Date(currentDoc.modification_date)) {
return previousDoc;
}
else {
return currentDoc;
}
});
haveChanges = (mostRecentDocument.id === document.id);
async.each(documents, function(deletedDocument, cb) {
if(deletedDocument.id !== mostRecentDocument.id) {
console.log("DELETE", deletedDocument.identifier);
anyfetch.deleteDocumentById(deletedDocument.id, function(err) {
if(err && err.toString().match(/404/)) {
err = null;
}
cb(err);
});
}
else {
cb(null);
}
}, cb);
}
], function(err) {
cb(err, haveChanges ? changes : null);
});
};