@lokalise/fastify-extras
Version:
Opinionated set of fastify plugins, commonly used in Lokalise
104 lines • 3.88 kB
JavaScript
import { isError } from '@lokalise/node-core';
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.healthcheckError ? 'FAIL' : 'HEALTHY';
if (entry.healthcheckError && opts.healthChecks[i]?.isMandatory) {
isFullyHealthy = false;
isPartiallyHealthy = false;
}
// Check if we are only partially healthy (only optional dependencies are failing)
if (isFullyHealthy && entry.healthcheckError && !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: (_, reply) => {
let isFullyHealthy = true;
let isPartiallyHealthy = false;
let healthChecks = {};
if (opts.healthChecks.length) {
const results = opts.healthChecks.map((healthcheck) => {
let healthcheckError;
try {
healthcheckError = healthcheck.checker(app);
}
catch (err) {
healthcheckError = isError(err) ? err : new Error(String(err));
}
if (healthcheckError) {
app.log.error(healthcheckError, `${healthcheck.name} healthcheck has failed`);
}
return {
name: healthcheck.name,
healthcheckError,
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 commonSyncHealthcheckPlugin = fp(plugin, {
fastify: '5.x',
name: 'common-sync-healthcheck-plugin',
});
//# sourceMappingURL=commonSyncHealthcheckPlugin.js.map