-
Notifications
You must be signed in to change notification settings - Fork 57
/
utils.js
86 lines (77 loc) · 2.41 KB
/
utils.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
79
80
81
82
83
84
85
86
/* global Buffer */
// use: let deferred = new Deferred();
/** Backwards compatible Promise.defer() function */
exports.Deferred = function() {
// credit: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred#Backwards_and_forwards_compatible_helper
this.resolve = null;
this.reject = null;
this.promise = new Promise(function(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}.bind(this));
Object.freeze(this);
};
exports.getAuthHeaderObject = function(accountId, applicationKey) {
if (!accountId) {
throw new Error('Invalid accountId');
}
if (!applicationKey) {
throw new Error('Invalid applicationKey');
}
let base64 = Buffer.from(accountId + ':' + applicationKey).toString('base64');
return {
Authorization: 'Basic ' + base64
};
};
exports.getAuthHeaderObjectWithToken = function(b2) {
if (!b2) {
throw new Error('Invalid B2 instance');
}
if (!b2.authorizationToken) {
throw new Error('Invalid authorizationToken');
}
return {
Authorization: b2.authorizationToken
};
};
exports.parseJson = function(jsonString) {
try {
return JSON.parse(jsonString);
} catch (e) {
// got error
}
};
exports.saveAuthContext = function (context, authResponse) {
context.authorizationToken = authResponse.authorizationToken;
context.apiUrl = authResponse.apiUrl;
context.downloadUrl = authResponse.downloadUrl;
context.accountId = authResponse.accountId;
};
exports.getProcessFileSuccess = function(deferred) {
return function(error, response, body, promise) {
deferred = deferred || promise;
if (error) {
deferred.reject(error);
} else if (response.statusCode !== 200) {
deferred.reject(response.statusMessage);
} else {
deferred.resolve(response);
}
};
};
exports.processResponseGeneric = function (deferred) {
return function(error, response, body, promise) {
deferred = deferred || promise;
if (error) {
return deferred.reject(error);
} else {
let genericResponse = exports.parseJson(body);
deferred.resolve(genericResponse);
}
};
};
exports.getUrlEncodedFileName = function(fileName) {
return fileName.split('/')
.map(encodeURIComponent)
.join('/');
};