Skip to content

Commit

Permalink
feat: add healthcheck to be used by Dockerfile
Browse files Browse the repository at this point in the history
  • Loading branch information
Fredrik Makila committed Sep 13, 2020
1 parent 8c8adf3 commit 73018ae
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/healthcheck/__tests__/healthcheck.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import http, { ClientRequest, IncomingMessage } from 'http';

jest.mock('http');
jest.mock('form-data');

const mockHttp = http as jest.Mocked<typeof http>;

interface KeyValue {
[key: string]: (response: IncomingMessage | Error) => void;
}

describe('healthcheck', () => {
const map: KeyValue = {};

const request = ({
on: (key: string, cb: (response: IncomingMessage | Error) => void) => {
map[key] = cb;
},
end: jest.fn()
} as unknown) as ClientRequest;

beforeEach(() => {
mockHttp.request.mockImplementationOnce(() => request);
});

it('should exit with error code 1 if an error occurs', () => {
const exitSpy = jest.spyOn(process, 'exit').mockImplementation();

require('../index');

map['error'](new Error());

expect(request.end).toHaveBeenCalled();
expect(exitSpy).toHaveBeenCalledWith(1);
});

it.each([
[1, 404],
[1, 422],
[1, 500],
[0, 200]
])('should exit with error code %s if the response has status code %s', (exitCode, statusCode) => {
const exitSpy = jest.spyOn(process, 'exit').mockImplementation();

require('../index');

const response = {
statusCode
} as Partial<IncomingMessage>;

map['response'](response as IncomingMessage);
expect(exitSpy).toHaveBeenCalledWith(exitCode);
});
});
37 changes: 37 additions & 0 deletions src/healthcheck/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import http from 'http';
import path from 'path';
import fs from 'fs';
import FormData from 'form-data';
import { info, trace } from '../logger';

const form = new FormData();
form.append('data', fs.createReadStream(path.resolve('src/healthcheck/rosterFile.rosz')));

const options = {
host: 'localhost',
port: '8000',
path: '/conversion',
timeout: 2000,
method: 'POST',
headers: form.getHeaders()
};

const request = http.request(options);
form.pipe(request);

request.on('response', (res) => {
info(`HEALTH CHECK STATUS: ${res.statusCode}`);
if (res.statusCode == 200) {
process.exit(0);
} else {
process.exit(1);
}
});

request.on('error', function (err) {
trace(err);
request.end();
process.exit(1);
});

export default {};
Binary file added src/healthcheck/rosterFile.rosz
Binary file not shown.

0 comments on commit 73018ae

Please sign in to comment.