diff --git a/lib/alias.js b/lib/alias.js index 38d1fb6..9c4e8ad 100644 --- a/lib/alias.js +++ b/lib/alias.js @@ -9,29 +9,75 @@ export default class Alias extends Now { async ls (deployment) { if (deployment) { const target = await this.findDeployment(deployment); - const res = await this._fetch(`/now/deployments/${target.uid}/aliases`); - const body = await res.json(); - return body.aliases; + + return this.retry(async (bail, attempt) => { + const res = await this._fetch(`/now/deployments/${target.uid}/aliases`); + const body = await res.json(); + return body.aliases; + }); } - const res = await this._fetch('/now/aliases'); - const body = await res.json(); - return body.aliases; + return this.retry(async (bail, attempt) => { + const res = await this._fetch('/now/aliases'); + const body = await res.json(); + return body.aliases; + }); } async rm (alias) { - const res = await this._fetch(`/now/aliases/${alias}`, { - method: 'DELETE' - }); - const body = await res.json(); - - if (res.status !== 200) { - const err = new Error('Deletion failed ' + body); + const _alias = await this.findAlias(alias); + if (!_alias) { + const err = new Error(`Alias not found by "${alias}". Run ${chalk.dim('`now alias ls`')} to see your aliases.`); err.userError = true; throw err; } - console.log(`${chalk.cyan('> Success!')}`); + return this.retry(async (bail, attempt) => { + const res = await this._fetch(`/now/aliases/${_alias.uid}`, { + method: 'DELETE' + }); + + if (403 === res.status) { + bail(new Error('Unauthorized')); + } + + if (res.status !== 200) { + const err = new Error('Deletion failed. Try again later.'); + throw err; + } + + console.log(`${chalk.cyan('> Success!')}`); + }); + } + + async findAlias (alias) { + const list = await this.ls(); + + let key, val; + if (/\./.test(alias)) { + val = toHost(alias); + key = 'alias'; + } else { + val = alias; + key = 'uid'; + } + + const _alias = list.find((d) => { + if (d[key] === val) { + if (this._debug) console.log(`> [debug] matched alias ${d.uid} by ${key} ${val}`); + return true; + } + + // match prefix + if (`${val}.now.sh` === d.alias) { + if (this._debug) console.log(`> [debug] matched alias ${d.uid} by url ${d.host}`); + return true; + } + + return false; + }); + + return _alias; } async findDeployment (deployment) {