Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(pg-v5): Move command pg:links to oclif #2770

Merged
merged 2 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions packages/cli/src/commands/pg/links/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import color from '@heroku-cli/color'
import {Command, flags} from '@heroku-cli/command'
import {Args, ux} from '@oclif/core'
import {getAddon, all} from '../../../lib/pg/fetcher'
import pgHost from '../../../lib/pg/host'
import type {Link} from '../../../lib/pg/types'

export default class Index extends Command {
static topic = 'pg';
static description = 'lists all databases and information on link';
static flags = {
app: flags.app({required: true}),
remote: flags.remote(),
};

static args = {
database: Args.string(),
};

public async run(): Promise<void> {
const {flags, args} = await this.parse(Index)
const {app} = flags
const {database} = args
let dbs
if (database)
dbs = await Promise.all([getAddon(this.heroku, app, database)])
else
dbs = await all(this.heroku, app)
if (dbs.length === 0)
throw new Error(`No databases on ${color.app(app)}`)
dbs = await Promise.all(dbs.map(async db => {
const {body: links} = await this.heroku.get<Link[]>(`/client/v11/databases/${db.id}/links`, {hostname: pgHost()})
db.links = links
return db
}))
let once: boolean
dbs.forEach(db => {
if (once)
ux.log()
else
once = true
ux.styledHeader(color.yellow(db.name))
if (db.links.message)
return ux.log(db.links.message)
if (db.links.length === 0)
return ux.log('No data sources are linked into this database')
db.links.forEach((link: Link) => {
ux.log(` * ${color.cyan(link.name)}`)
const remoteAttachmentName = link.remote?.attachment_name || ''
const remoteName = link.remote?.name || ''
const remoteLinkText = `${color.green(remoteAttachmentName)} (${color.yellow(remoteName)})`
ux.styledObject({
created_at: link.created_at,
remote: remoteLinkText,
})
})
})
}
}
31 changes: 28 additions & 3 deletions packages/cli/src/lib/pg/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,31 @@ export async function arbitraryAppDB(heroku: APIClient, app: string) {
return addon
}

function getAttachmentNamesByAddon(attachments: AddOnAttachmentWithConfigVarsAndPlan[]) {
return attachments.reduce((results: any, a) => {
results[a.addon.id] = (results[a.addon.id] || []).concat(a.name)
return results
}, {})
}

export async function all(heroku: APIClient, app_id: string) {
const {uniqBy} = require('lodash')

pgDebug(`fetching all DBs on ${app_id}`)

const attachments = await allAttachments(heroku, app_id)
let addons = attachments.map(a => a.addon)

// Get the list of attachment names per addon here and add to each addon obj
const attachmentNamesByAddon = getAttachmentNamesByAddon(attachments)
addons = uniqBy(addons, 'id')
addons.forEach(addon => {
addon.attachment_names = attachmentNamesByAddon[addon.id]
})

return addons
}

async function matchesHelper(heroku: APIClient, app: string, db: string, namespace?: string): Promise<{matches: AddOnAttachment[] | null, error?: AmbiguousError | NotFound}> {
debug(`fetching ${db} on ${app}`)

Expand Down Expand Up @@ -72,7 +97,7 @@ export async function attachment(heroku: APIClient, app: string, db = 'DATABASE_
if (attachments.length === 0) {
throw new Error(`${color.app(app)} has no databases`)
}

console.log('hi', JSON.stringify(attachments))
matches = attachments.filter(attachment => config[db] && config[db] === config[getConfigVarName(attachment.config_vars as string[])])

if (matches.length === 0) {
Expand All @@ -96,8 +121,8 @@ export async function attachment(heroku: APIClient, app: string, db = 'DATABASE_
throw error
}

async function allAttachments(heroku: APIClient, app: string) {
const {body: attachments} = await heroku.get<AddOnAttachmentWithConfigVarsAndPlan[]>(`/apps/${app}/addon-attachments`, {
async function allAttachments(heroku: APIClient, app_id: string) {
const {body: attachments} = await heroku.get<AddOnAttachmentWithConfigVarsAndPlan[]>(`/apps/${app_id}/addon-attachments`, {
headers: {'Accept-Inclusion': 'addon:plan,config_vars'},
})
return attachments.filter((a: AddOnAttachmentWithConfigVarsAndPlan) => a.addon.plan?.name?.startsWith('heroku-postgresql'))
Expand Down
13 changes: 10 additions & 3 deletions packages/cli/src/lib/pg/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,21 @@ export type BackupTransfer = {
updated_at: string,
warnings: number,
}
export type AddOnWithPlan = Required<Heroku.AddOnAttachment['addon']> & { plan: Required<Heroku.AddOn['plan']> }
export type AddOnWithRelatedData = Required<Heroku.AddOnAttachment['addon']> & {
attachment_names?: string[],
links?: Link[],
plan: Required<Heroku.AddOn['plan']>
}
export type AddOnAttachmentWithConfigVarsAndPlan = Required<Heroku.AddOnAttachment> & {
config_vars: Heroku.AddOn['config_vars']
addon: AddOnWithPlan
addon: AddOnWithRelatedData
}
export type Link = {
attachment_name?: string,
created_at: string,
message: string,
name: string
name: string,
remote?: Link,
}
export type CredentialsInfo = {
database: string
Expand Down
67 changes: 67 additions & 0 deletions packages/cli/test/unit/commands/pg/links/index.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {stdout} from 'stdout-stderr'
import heredoc from 'tsheredoc'
import Cmd from '../../../../../src/commands/pg/links/index'
import runCommand from '../../../../helpers/runCommand'
import * as nock from 'nock'
import expectOutput from '../../../../helpers/utils/expectOutput'
import * as fixtures from '../../../../fixtures/addons/fixtures'

describe('pg:links', () => {
const addon = fixtures.addons['www-db']
const appName = 'myapp'
const redisLink = {
name: 'redis-link-1',
created_at: '100',
remote: {
attachment_name: 'REDIS',
name: 'redis-001',
},
}

afterEach(() => {
nock.cleanAll()
})

it('shows links', async () => {
nock('https://api.heroku.com')
.get(`/apps/${appName}/addon-attachments`)
.reply(200, [{addon}])
nock('https://api.data.heroku.com')
.get(`/client/v11/databases/${addon.id}/links`)
.reply(200, [redisLink])

await runCommand(Cmd, [
'--app',
appName,
])
expectOutput(stdout.output, heredoc(`
=== ${addon.name}

* redis-link-1
created_at: 100
remote: REDIS (redis-001)
`))
})

it('shows links when args are present', async () => {
nock('https://api.heroku.com')
.post('/actions/addon-attachments/resolve')
.reply(200, [{addon}])
nock('https://api.data.heroku.com')
.get(`/client/v11/databases/${addon.id}/links`)
.reply(200, [redisLink])

await runCommand(Cmd, [
'--app',
'myapp',
'test-database',
])
expectOutput(stdout.output, heredoc(`
=== ${addon.name}

* redis-link-1
created_at: 100
remote: REDIS (redis-001)
`))
})
})
46 changes: 0 additions & 46 deletions packages/pg-v5/commands/links/index.js

This file was deleted.

1 change: 0 additions & 1 deletion packages/pg-v5/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ exports.commands = flatten([
require('./commands/info'),
require('./commands/kill'),
require('./commands/killall'),
require('./commands/links'),
require('./commands/links/destroy'),
require('./commands/locks'),
require('./commands/outliers'),
Expand Down
66 changes: 0 additions & 66 deletions packages/pg-v5/test/unit/commands/links/index.unit.test.js

This file was deleted.

Loading