UNPKG

2.18 kBJavaScriptView Raw
1'use strict'
2
3const cli = require('heroku-cli-util')
4const co = require('co')
5
6function * run (context, heroku) {
7 const fetcher = require('../lib/fetcher')(heroku)
8 const {app, args} = context
9 const db = yield fetcher.addon(app, args.database)
10
11 yield cli.action(`Ensuring an alternate alias for existing ${cli.color.configVar('DATABASE_URL')}`, co(function * () {
12 // Finds or creates a non-DATABASE attachment for the DB currently
13 // attached as DATABASE.
14 //
15 // If current DATABASE is attached by other names, return one of them.
16 // If current DATABASE is only attachment, create a new one and return it.
17 // If no current DATABASE, return nil.
18 let attachments = yield heroku.get(`/apps/${app}/addon-attachments`)
19 let current = attachments.find(a => a.name === 'DATABASE')
20 if (!current) return
21 if (current.addon.name === db.name) throw new Error(`${cli.color.addon(db.name)} is already promoted on ${cli.color.app(app)}`)
22 let existing = attachments.filter(a => a.addon.id === current.addon.id).find(a => a.name !== 'DATABASE')
23 if (existing) return cli.action.done(cli.color.configVar(existing.name + '_URL'))
24
25 // The current add-on occupying the DATABASE attachment has no
26 // other attachments. In order to promote this database without
27 // error, we can create a secondary attachment, just-in-time.
28
29 let backup = yield heroku.post('/addon-attachments', {
30 body: {
31 app: {name: app},
32 addon: {name: current.addon.name},
33 confirm: app
34 }
35 })
36 cli.action.done(cli.color.configVar(backup.name + '_URL'))
37 }))
38
39 yield cli.action(`Promoting ${cli.color.addon(db.name)} to ${cli.color.configVar('DATABASE_URL')} on ${cli.color.app(app)}`, co(function * () {
40 yield heroku.post('/addon-attachments', {
41 body: {
42 name: 'DATABASE',
43 app: {name: app},
44 addon: {name: db.name},
45 confirm: app
46 }
47 })
48 }))
49}
50
51module.exports = {
52 topic: 'pg',
53 command: 'promote',
54 description: 'sets DATABASE as your DATABASE_URL',
55 needsApp: true,
56 needsAuth: true,
57 args: [{name: 'database'}],
58 run: cli.command({preauth: true}, co.wrap(run))
59}