chore(api): log growthbook initialization failures (#59889)

Co-authored-by: Mrugesh Mohapatra <1884376+raisedadead@users.noreply.github.com>
Co-authored-by: Shaun Hamilton <shauhami020@gmail.com>
This commit is contained in:
Oliver Eyton-Williams
2025-04-22 18:36:27 +02:00
committed by GitHub
parent 6d06eaa5c0
commit 37028f2bb8
3 changed files with 41 additions and 8 deletions

View File

@@ -2,7 +2,6 @@ import fastifyAccepts from '@fastify/accepts';
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUI from '@fastify/swagger-ui';
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { GrowthBook } from '@growthbook/growthbook';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import uriResolver from 'fast-uri';
@@ -60,12 +59,6 @@ type FastifyInstanceWithTypeProvider = FastifyInstance<
TypeBoxTypeProvider
>;
declare module 'fastify' {
interface FastifyInstance {
gb: GrowthBook;
}
}
// Options that fastify uses
const ajv = new Ajv({
coerceTypes: 'array', // change data type of data to match type keyword

View File

@@ -0,0 +1,29 @@
import Fastify, { type FastifyInstance } from 'fastify';
import growthBook from './growth-book';
const captureException = jest.fn();
describe('growth-book', () => {
let fastify: FastifyInstance;
beforeAll(() => {
fastify = Fastify();
// @ts-expect-error we're mocking the Sentry plugin
fastify.Sentry = { captureException };
});
afterAll(async () => {
await fastify.close();
});
it('should log the error if the GrowthBook initialization fails', async () => {
const spy = jest.spyOn(fastify.log, 'error');
await fastify.register(growthBook, {
apiHost: 'invalid-url',
clientKey: 'invalid-key'
});
expect(spy).toHaveBeenCalled();
expect(captureException).toHaveBeenCalled();
});
});

View File

@@ -2,9 +2,20 @@ import { GrowthBook, Options } from '@growthbook/growthbook';
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
declare module 'fastify' {
interface FastifyInstance {
gb: GrowthBook;
}
}
const growthBook: FastifyPluginAsync<Options> = async (fastify, options) => {
const gb = new GrowthBook(options);
await gb.init({ timeout: 3000 });
const res = await gb.init({ timeout: 3000 });
if (res.error) {
fastify.log.error(res.error, 'Failed to initialize GrowthBook');
fastify.Sentry.captureException(res.error);
}
fastify.decorate('gb', gb);