-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
90 lines (78 loc) · 2.51 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
79
80
81
82
83
84
85
86
87
88
89
90
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const debug = require('debug')('push2cloud-cf-adapter');
const EventEmitter = require('events');
const functions = [];
const functionsPath = path.join(__dirname, 'fns');
fs.readdirSync(functionsPath).forEach((fileName) => {
var joinedPath = path.join(functionsPath, fileName);
if (path.extname(fileName) === '.js') {
var required = require(joinedPath);
functions.push({ name: path.basename(fileName, '.js'), module: required });
}
});
module.exports = (options) => {
options = options || {};
var defaults = {
api: 'https://api.run.pivotal.io',
rejectUnauthorized: true,
maxRetries: 3,
delay: 1000,
delayFactor: 1
};
_.defaults(options, defaults);
const api = { options };
functions.forEach((fn) => {
const orgFn = fn.module(api);
api[fn.name] = function(opts) {
var additionalInfos;
if (opts) {
if (opts.name) additionalInfos = ' ' + opts.name;
if (!additionalInfos && opts.app) additionalInfos = ' ' + opts.app;
if (!additionalInfos && opts.hostname) additionalInfos = ' ' + opts.hostname;
if (!additionalInfos) additionalInfos = '';
}
if (arguments.length === 0 || typeof arguments[arguments.length - 1] !== 'function') {
var args = _.toArray(arguments);
// called as promise..
debug(`called ${fn.name} as promise...${additionalInfos}`);
return new Promise((resolve, reject) => {
args.push(function(err) {
var responseArgs = _.toArray(arguments);
responseArgs.shift();
if (err) {
return reject(err);
}
if (responseArgs.length === 0) {
return resolve();
}
if (responseArgs.length === 1) {
return resolve(responseArgs[0]);
}
resolve(responseArgs);
});
orgFn.apply(api, args);
});
} else {
// called normally...
debug(`called ${fn.name}...${additionalInfos}`);
orgFn.apply(api, arguments);
}
};
});
api.graceRequestHandlers = [];
api.attachRetryHandler = (fn) => {
if (_.isFunction(fn) && api.graceRequestHandlers.indexOf(fn) < 0) {
api.graceRequestHandlers.push(fn);
} else {
fn.forEach((f) => {
if (api.graceRequestHandlers.indexOf(f) < 0) {
api.graceRequestHandlers.push(f);
}
});
}
};
api.stats = new EventEmitter();
return api;
};