Skip to content

Commit

Permalink
feat: make result for port command type safe
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexZeitler committed Apr 14, 2021
1 parent b6eec00 commit 70a98f4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
32 changes: 29 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ export interface IDockerComposeOptions {
env?: NodeJS.ProcessEnv
}

export type DockerComposePortResult = {
address: string
port: number
}

export interface IDockerComposeLogOptions extends IDockerComposeOptions {
follow?: boolean
}
Expand All @@ -27,6 +32,13 @@ export interface IDockerComposeResult {
err: string
}

export type TypedDockerComposeResult<T> = {
exitCode: number | null
out: string
err: string
result: T
}

/**
* Converts supplied yml files to cli arguments
* https://docs.docker.com/compose/reference/overview/#use--f-to-specify-name-and-path-of-one-or-more-compose-files
Expand Down Expand Up @@ -343,14 +355,28 @@ export const logs = function (
return execCompose('logs', args, options)
}

export const port = function (
export const port = async function (
service: string,
containerPort: string | number,
options?: IDockerComposeOptions
): Promise<IDockerComposeResult> {
): Promise<TypedDockerComposeResult<DockerComposePortResult>> {
const args = [service, containerPort]

return execCompose('port', args, options)
try {
const result = await execCompose('port', args, options)
const [address, port] = result.out.split(':')
return {
exitCode: result.exitCode,
out: result.out,
err: result.err,
result: {
address,
port: Number(port)
}
}
} catch (error) {
return Promise.reject(error)
}
}

export const version = function (
Expand Down
2 changes: 1 addition & 1 deletion test/docker-compose-2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ services:
environment:
NGINX_PORT: 8888
ports:
- "8888"
- 8888:8888
5 changes: 3 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,10 @@ test('build accepts config as string', async (): Promise<void> => {
}

await compose.upAll(config)
const port = await compose.port('web', 8888, config)
const result = await compose.port('web', 8888, config)

expect(port.out).toMatch(/.*:[0-9]{1,5}/)
expect(result.result.address).toBe('0.0.0.0')
expect(result.result.port).toBe(8888)
await compose.down(config)
})

Expand Down

0 comments on commit 70a98f4

Please sign in to comment.