From 50aba39a2fe46ec31968de5bc1e00837667792a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Birm=C3=A9?= Date: Thu, 5 Dec 2024 10:58:30 +0100 Subject: [PATCH] chore: refactor passing openai api key (#5) --- package.json | 2 +- src/api.test.ts | 2 +- src/api.ts | 4 ++-- src/server.ts | 9 ++++++++- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 367f9a0..e88df1d 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "1.0.0", "description": "White-label AI chat service ready to be embedded on your site", "scripts": { - "test": "OPENAI_API_KEY=dummy jest", + "test": "jest", "prepare": "husky install", "lint": "eslint .", "pretty": "prettier --check --ignore-unknown .", diff --git a/src/api.test.ts b/src/api.test.ts index 9f5856f..91891c9 100644 --- a/src/api.test.ts +++ b/src/api.test.ts @@ -2,7 +2,7 @@ import api from './api'; describe('api', () => { it('responds with hello, world!', async () => { - const server = api({ title: 'my awesome service' }); + const server = api({ title: 'my awesome service', openAiApiKey: 'dummy' }); const response = await server.inject({ method: 'GET', url: '/api' diff --git a/src/api.ts b/src/api.ts index bcc6380..de8ba34 100644 --- a/src/api.ts +++ b/src/api.ts @@ -7,7 +7,6 @@ import { Static, Type } from '@sinclair/typebox'; import { FastifyPluginCallback } from 'fastify'; import apiService from './api_service'; -const openAiApiKey = process.env.OPENAI_API_KEY as string; const HelloWorld = Type.String({ description: 'The magical words!' }); @@ -40,6 +39,7 @@ const healthcheck: FastifyPluginCallback = ( export interface ApiOptions { title: string; + openAiApiKey: string; } export default (opts: ApiOptions) => { @@ -69,7 +69,7 @@ export default (opts: ApiOptions) => { api.register(apiService, { prefix: '/api/v1', - openAiApiKey: openAiApiKey as string + openAiApiKey: opts.openAiApiKey }); return api; diff --git a/src/server.ts b/src/server.ts index aa9b178..5d8968a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2,7 +2,14 @@ import fastifyStatic from '@fastify/static'; import path from 'path'; import api from './api'; -const server = api({ title: 'White Label AI chat service' }); +const OPENAI_API_KEY = process.env.OPENAI_API_KEY; +if (!OPENAI_API_KEY) { + throw new Error('OPENAI_API_KEY is required'); +} +const server = api({ + title: 'White Label AI chat service', + openAiApiKey: OPENAI_API_KEY +}); server.register(fastifyStatic, { root: path.join(__dirname, '../out'),