@lokalise/fastify-extras
Version:
Opinionated set of fastify plugins, commonly used in Lokalise
97 lines • 3.59 kB
JavaScript
import fp from 'fastify-plugin';
function resolveHealthcheckResults(results, opts) {
const healthChecks = {};
let isFullyHealthy = true;
let isPartiallyHealthy = false;
// Return detailed healthcheck results
for (let i = 0; i < results.length; i++) {
const entry = results[i];
if (!entry)
continue;
healthChecks[entry.name] = entry.result.error ? 'FAIL' : 'HEALTHY';
if (entry.result.error && opts.healthChecks[i]?.isMandatory) {
isFullyHealthy = false;
isPartiallyHealthy = false;
}
// Check if we are only partially healthy (only optional dependencies are failing)
if (isFullyHealthy && entry.result.error && !opts.healthChecks[i]?.isMandatory) {
isFullyHealthy = false;
isPartiallyHealthy = true;
}
}
return {
isFullyHealthy,
isPartiallyHealthy,
healthChecks,
};
}
function addRoute(app, opts, routeOpts) {
const responsePayload = opts.responsePayload ?? {};
app.route({
url: routeOpts.url,
method: 'GET',
logLevel: opts.logLevel ?? 'info',
schema: {
// hide route from swagger plugins
hide: true,
},
handler: async (_, reply) => {
let isFullyHealthy = true;
let isPartiallyHealthy = false;
let healthChecks = {};
if (opts.healthChecks.length) {
const results = await Promise.all(opts.healthChecks.map(async (healthcheck) => {
const result = await healthcheck.checker(app);
if (result.error) {
app.log.error(result.error, `${healthcheck.name} healthcheck has failed`);
}
return {
name: healthcheck.name,
result,
isMandatory: healthcheck.isMandatory,
};
}));
const resolvedHealthcheckResponse = resolveHealthcheckResults(results, opts);
healthChecks = resolvedHealthcheckResponse.healthChecks;
isFullyHealthy = resolvedHealthcheckResponse.isFullyHealthy;
isPartiallyHealthy = resolvedHealthcheckResponse.isPartiallyHealthy;
}
const extraInfo = opts.infoProviders?.map((infoProvider) => ({
name: infoProvider.name,
value: infoProvider.dataResolver(),
}));
const heartbeat = isFullyHealthy
? 'HEALTHY'
: isPartiallyHealthy
? 'PARTIALLY_HEALTHY'
: 'FAIL';
const response = {
...responsePayload,
heartbeat,
...(routeOpts.isPublicRoute
? {}
: { checks: healthChecks, ...(extraInfo && { extraInfo }) }),
};
return reply.status(isFullyHealthy || isPartiallyHealthy ? 200 : 500).send(response);
},
});
}
const plugin = (app, opts, done) => {
const isRootRouteEnabled = opts.isRootRouteEnabled ?? true;
if (isRootRouteEnabled) {
addRoute(app, opts, {
url: '/',
isPublicRoute: true,
});
}
addRoute(app, opts, {
url: '/health',
isPublicRoute: false,
});
done();
};
export const commonHealthcheckPlugin = fp(plugin, {
fastify: '5.x',
name: 'common-healthcheck-plugin',
});
//# sourceMappingURL=commonHealthcheckPlugin.js.map