backend-app-api: healthcheck middleware

Signed-off-by: Vincenzo Scamporlino <vincenzos@spotify.com>
This commit is contained in:
Vincenzo Scamporlino
2024-05-17 11:20:10 +02:00
parent 8dc15aae58
commit 8bbbc314f1
2 changed files with 67 additions and 0 deletions
@@ -0,0 +1,33 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import express from 'express';
import request from 'supertest';
import { createHealthcheck } from './createHealthcheck';
describe('createHealthcheck', () => {
it('should return a router with a healthcheck endpoint', async () => {
const hc = createHealthcheck();
const app = express().use(hc.router);
let response = await request(app).get('/healthcheck').expect(200);
expect(response.body).toEqual({ status: 'ok' });
hc.addHandler(async () => ({ allgood: true }));
response = await request(app).get('/healthcheck').expect(200);
expect(response.body).toEqual({ allgood: true });
});
});
@@ -0,0 +1,34 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Request, Response } from 'express';
import Router from 'express-promise-router';
export function createHealthcheck() {
const router = Router();
let handler = () => Promise.resolve({ status: 'ok' });
router.get('/healthcheck', async (_request: Request, response: Response) => {
const status = await handler();
response.json(status);
});
return {
router,
addHandler: (newHandler: () => Promise<any>) => {
handler = newHandler;
},
};
}