Browse Source

feat: prod/dev env settings

Yidadaa 2 years ago
parent
commit
144eb68414
3 changed files with 39 additions and 15 deletions
  1. 1 0
      app/api/chat/config.template.ts
  2. 30 14
      app/api/chat/route.ts
  3. 8 1
      yarn.lock

+ 1 - 0
app/api/chat/config.template.ts

@@ -0,0 +1 @@
+export const apiKey = "your dev api key here";

+ 30 - 14
app/api/chat/route.ts

@@ -1,27 +1,43 @@
 import { OpenAIApi, Configuration } from "openai";
-import { apiKey } from "./config";
 import { ChatRequest } from "./typing";
 
-// set up openai api client
-const config = new Configuration({
-  apiKey,
-});
-const openai = new OpenAIApi(config);
+const isProd = process.env.NODE_ENV === "production";
+
+let openai: OpenAIApi | undefined;
+async function initService() {
+  let apiKey = process.env.OPENAI_API_KEY;
+
+  if (!isProd) {
+    apiKey = await (await import("./config")).apiKey;
+  }
+
+  openai = new OpenAIApi(
+    new Configuration({
+      apiKey,
+    })
+  );
+}
 
 export async function POST(req: Request) {
+  if (!openai) {
+    await initService();
+  }
+
   try {
     const requestBody = (await req.json()) as ChatRequest;
-    const completion = await openai.createChatCompletion(
+    const completion = await openai!.createChatCompletion(
       {
         ...requestBody,
       },
-      {
-        proxy: {
-          protocol: "socks",
-          host: "127.0.0.1",
-          port: 7890,
-        },
-      }
+      isProd
+        ? {}
+        : {
+            proxy: {
+              protocol: "socks",
+              host: "127.0.0.1",
+              port: 7890,
+            },
+          }
     );
 
     return new Response(JSON.stringify(completion.data));

+ 8 - 1
yarn.lock

@@ -1742,7 +1742,14 @@ cosmiconfig@^7.0.1:
     path-type "^4.0.0"
     yaml "^1.10.0"
 
-cross-spawn@^7.0.2, cross-spawn@^7.0.3:
+cross-env@^7.0.3:
+  version "7.0.3"
+  resolved "https://registry.npmmirror.com/cross-env/-/cross-env-7.0.3.tgz#865264b29677dc015ba8418918965dd232fc54cf"
+  integrity sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==
+  dependencies:
+    cross-spawn "^7.0.1"
+
+cross-spawn@^7.0.1, cross-spawn@^7.0.2, cross-spawn@^7.0.3:
   version "7.0.3"
   resolved "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6"
   integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==