UNPKG

@lokalise/fastify-extras

Version:

Opinionated set of fastify plugins, commonly used in Lokalise

77 lines 3.18 kB
import { isError } from '@lokalise/node-core'; import fp from 'fastify-plugin'; function plugin(app, opts, done) { const responsePayload = opts.responsePayload ?? {}; app.route({ url: opts.url ?? '/health', method: 'GET', logLevel: opts.logLevel ?? 'info', schema: { // hide route from swagger plugins hide: true, }, // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: <explanation> handler: async (_, reply) => { let isFullyHealthy = true; let isPartiallyHealthy = false; const healthChecks = {}; if (opts.healthChecks.length) { const results = await Promise.all(opts.healthChecks.map(async (healthcheck) => { let result; try { result = await healthcheck.checker(app); } catch (err) { result = { error: isError(err) ? err : new Error(String(err)) }; } if (result.error) { app.log.error(result.error, `${healthcheck.name} healthcheck has failed`); } return { name: healthcheck.name, result, isMandatory: healthcheck.isMandatory, }; })); 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; } } } const extraInfo = opts.infoProviders ? opts.infoProviders.map((infoProvider) => { return { name: infoProvider.name, value: infoProvider.dataResolver(), }; }) : undefined; return reply.status(isFullyHealthy || isPartiallyHealthy ? 200 : 500).send({ ...responsePayload, checks: healthChecks, ...(extraInfo && { extraInfo }), heartbeat: isFullyHealthy ? 'HEALTHY' : isPartiallyHealthy ? 'PARTIALLY_HEALTHY' : 'FAIL', }); }, }); done(); } /** * @deprecated use commonSyncHealthcheckPlugin instead */ export const publicHealthcheckPlugin = fp(plugin, { fastify: '5.x', name: 'public-healthcheck-plugin', }); //# sourceMappingURL=publicHealthcheckPlugin.js.map