UNPKG

@mailbiz/javascript-tracker

Version:
89 lines (79 loc) 2.42 kB
import http from 'http'; import Docker from 'dockerode'; import { Writable } from 'stream'; export interface DockerWrapper { url: string; container: Docker.Container; } const docker = new Docker(); export const start = () => { return docker .createContainer({ Image: 'snowplow/snowplow-micro:1.1.2', AttachStdin: false, AttachStdout: true, AttachStderr: true, Tty: true, Cmd: ['--collector-config', '/config/micro.conf', '--iglu', '/config/iglu.json'], OpenStdin: false, StdinOnce: false, HostConfig: { Binds: [`${process.cwd()}/test/micro-config:/config`], PortBindings: { '9090/tcp': [ { HostIp: '', HostPort: '', }, ], }, }, ExposedPorts: { '9090/tcp': {}, }, }) .then((c) => { return c.start().then(() => { const outs = new Writable({ write(chunk, _, callback) { const found = chunk.toString().includes('REST interface bound'); if (found) this.end(); callback(); }, }); c.attach({ stream: true, stdout: true, stderr: true }, (_, stream) => { stream?.pipe(process.stdout); stream?.pipe(outs); }); return new Promise<DockerWrapper>((resolve) => { outs.on('finish', () => c.inspect().then((info) => { resolve({ container: c, url: `mailbiz-js-tracker.local:${info.NetworkSettings.Ports['9090/tcp'][0].HostPort}`, }); }) ); }); }); }); }; export const stop = (container: Docker.Container) => container.stop().then(() => container.remove()); const createMicroCall = (url: string) => () => new Promise((resolve, reject) => { const req = http.request(url, (res) => { let body = ''; res.on('data', (chunk) => { body += chunk; }); res.on('end', () => { resolve(body); }); }); req.on('error', reject); req.end(); }); export const fetchResults = (containerUrl: string) => createMicroCall(`http://${containerUrl}/micro/good`)().then((good: unknown) => JSON.parse(good as string)); export const clearCache = (containerUrl: string) => createMicroCall(`http://${containerUrl}/micro/reset`)().then((_: unknown) => true);