All files / src docker.ts

37.5% Statements 12/32
0% Branches 0/3
0% Functions 0/4
34.61% Lines 9/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 712x 2x   2x 2x   2x 2x   2x                                     2x               2x                                                                    
import { containerExec, imageExists, pullImageAsync } from 'dockerode-utils';
import Docker from 'dockerode';
 
export { Docker };
export { containerExec } from 'dockerode-utils';
 
const CONTAINER_IMAGE = 'postgres:12.16-alpine';
const CONTAINER_NAME = 'cardano-test';
 
export const removePostgresContainer = async (): Promise<void> => {
  const docker = new Docker();
  try {
    const container = docker.getContainer(CONTAINER_NAME);
    try {
      await container.stop();
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      // 304 = container already stopped
      Iif (error.statusCode !== 304) throw error;
    }
    await container.remove({ v: true });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
  } catch (error: any) {
    // 404 = container not found
    Iif (error.statusCode !== 404) throw error;
  }
};
 
const ensurePgServiceReadiness = async (container: Docker.Container, user: string, db: string) => {
  await containerExec(container, [
    'bash',
    '-c',
    `until psql -U ${user} ${db} -c "SELECT 1" > /dev/null 2>&1 ; do echo "waiting pg service to be ready"; sleep 1; done`
  ]);
};
 
export const setupPostgresContainer = async (
  user: string,
  password: string,
  port: string,
  binds: Docker.HostConfig['Binds'],
  checkDb: string
) => {
  const docker = new Docker();
  const needsToPull = !(await imageExists(docker, CONTAINER_IMAGE));
 
  Iif (needsToPull) await pullImageAsync(docker, CONTAINER_IMAGE);
 
  await removePostgresContainer();
 
  const container = await docker.createContainer({
    Env: [`POSTGRES_PASSWORD=${password}`, `POSTGRES_USER=${user}`],
    HostConfig: {
      Binds: binds,
      PortBindings: {
        '5432/tcp': [
          {
            HostPort: port
          }
        ]
      }
    },
    Image: CONTAINER_IMAGE,
    name: CONTAINER_NAME
  });
  await container.start();
 
  await ensurePgServiceReadiness(container, user, checkDb);
  return container;
};