-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo.js
More file actions
77 lines (60 loc) · 1.8 KB
/
Copy pathdo.js
File metadata and controls
77 lines (60 loc) · 1.8 KB
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
// Import a module
const Promise = require('bluebird')
const DigitalOceanAPI = require('doapi')
const config = loadConfig()
// Create an instance with your API V2 credentials
const api = new DigitalOceanAPI({ token: config.digitalocean })
const ip = api.dropletNew(config.opts)
.then(getId)
.then(api.dropletGet)
.then(getDropletNetwork)
.catch(exit)
displayIP(ip);
function loadConfig() {
const isConfigSetup = require('fs').existsSync('config.js')
if (!isConfigSetup) {
console.log('Config.js file missing!')
console.log('Copy config.example.js to config.js and fill in your digital ocean API key')
return exit(new Error('MISSING_CONFIG_ERROR'))
}
return require('./config')
}
function debug() {
if ((process.env.DEBUG === 'true')) return console.log.apply(console, [].slice.apply(arguments))
}
const exit = (e) => {
console.log(e)
process.exit(1)
}
function getDropletNetwork(d) {
debug('getDropletNetwork');
if (!d || !d.networks ) return Promise.reject(new Error('Invalid droplet'))
if (d.networks.v4.length > 0) {
debug('getDropletNetwork resolving with: %j', d.networks)
return Promise.resolve(d.networks)
} else {
debug('getDropletNetwork: not yet populated, retrying...')
return Promise.delay(2000, d.id)
.then(api.dropletGet)
.then(getDropletNetwork)
}
}
function display(ip) {
debug('display', ip)
const address = ip && ip.v4 && ip.v4[0] && ip.v4[0].ip_address
if (!address) {
return Promise.reject(new Error('Invalid networking format:\n' + JSON.stringify(ip)))
}
console.log(address)
return Promise.resolve(ip)
}
function displayIP(ip) {
ip
.then(display)
.catch(exit)
}
function getId(d) {
return (d && d.id)
? Promise.resolve(d.id)
: Promise.reject(new Error('getId invalid data'))
}