Skip to content

Commit f696043

Browse files
committed
Add getDroplet_
1 parent 0d5f7c0 commit f696043

1 file changed

Lines changed: 38 additions & 11 deletions

File tree

src/cloud/digitalocean/provisioner.ts

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const STATUS_CODES: { [k: string]: string; } = {
3636
};
3737

3838
const ERR_CODES: { [k: string]: string; } = {
39+
'VM_AE': 'VM already exists.',
3940
'VM_DNE': 'VM does not exist',
4041
'CLOUD_ERR': 'Error from cloud provider'
4142
};
@@ -67,9 +68,17 @@ class Provisioner {
6768
return this.doOAuth_().then((oauthObj: any) => {
6869
this.state_.oauth = oauthObj;
6970
return this.getSshKey_(name);
70-
// Get SSH keys
7171
}).then((keys: KeyPair) => {
72+
// Get SSH keys
7273
this.state_.ssh = keys;
74+
return this.getDroplet_(name);
75+
}).then((resp: any) => {
76+
if (resp.droplet) {
77+
return Promise.reject({
78+
'errcode': 'VM_AE',
79+
'message': 'Droplet ' + name + ' already exists'
80+
});
81+
}
7382
return this.setupDigitalOcean_(name, region, image, size);
7483
// Setup Digital Ocean (SSH key + droplet)
7584
}).then(() => {
@@ -118,6 +127,32 @@ class Provisioner {
118127
* @return {Promise.<void>}
119128
*/
120129
private destroyServer_ = (name: string): Promise<void> => {
130+
return this.doRequest_('GET', 'droplets').then((resp: any) => {
131+
// Find and delete the server with the same name
132+
return this.getDroplet_(name);
133+
}).then((resp :any) => {
134+
if (!resp.droplet) {
135+
return Promise.reject({
136+
'errcode': 'VM_DNE',
137+
'message': 'Droplet ' + name + ' doesnt exist'
138+
});
139+
}
140+
return this.doRequest_('DELETE', 'droplets/' + resp.droplet.id);
141+
}).then((resp: any) => {
142+
if (resp.status.startsWith('204')) {
143+
return Promise.resolve<void>();
144+
}
145+
return Promise.reject(new Error('error deleting droplet'));
146+
});
147+
}
148+
149+
/**
150+
* Finds a droplet with this name
151+
* @param {String} droplet name, as a string
152+
* @return {Promise.<Object>}, returns droplet if exists
153+
* or undefined if it does not exist
154+
*/
155+
private getDroplet_ = (name: string) : Promise<Object> => {
121156
return this.doRequest_('GET', 'droplets').then((resp: any) => {
122157
// Find and delete the server with the same name
123158
for (var i = 0; i < resp.droplets.length; i++) {
@@ -127,17 +162,9 @@ class Provisioner {
127162
});
128163
}
129164
}
130-
return Promise.reject({
131-
'errcode': 'VM_DNE',
132-
'message': 'Droplet ' + name + ' doesnt exist'
165+
return Promise.resolve({
166+
droplet: undefined
133167
});
134-
}).then((resp: any) => {
135-
return this.doRequest_('DELETE', 'droplets/' + resp.droplet.id);
136-
}).then((resp: any) => {
137-
if (resp.status.startsWith('204')) {
138-
return Promise.resolve<void>();
139-
}
140-
return Promise.reject(new Error('error deleting droplet'));
141168
});
142169
}
143170

0 commit comments

Comments
 (0)