-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
58 lines (52 loc) · 1.56 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import dotenv from "dotenv";
import express, { Request, Response } from "express";
import OpenAI from "openai";
import path from "path";
const PORT = parseInt(process.env.PORT || "");
const HOST = process.env.HOST || "localhost";
const OPENAI_SECRET_KEY = process.env.OPENAI_SECRET_KEY;
dotenv.config();
const app = express();
app.use(express.json());
app.use("/", express.static(path.join(__dirname, "public")));
app.use((req: Request, res: Response, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "*");
if (req.method === "OPTIONS") {
res.sendStatus(200);
} else {
next();
}
});
app.get("/users/:id", (req: Request, res: Response) => {
res.json({
id: req.params.id,
name: "ゲスト",
image: `http:${HOST}:${PORT}/user.png`,
});
});
app.post("/translates", async (req: Request, res: Response) => {
const { text } = req.body;
const prompt = `次の文章を英訳してください。\n\n${text}`;
const openai = new OpenAI({
apiKey: OPENAI_SECRET_KEY,
});
try {
const response = await openai.chat.completions.create({
messages: [{ role: "user", content: prompt }],
model: "gpt-3.5-turbo",
});
res.json({
id: "1",
text: response.choices[0].message.content?.trim() ?? text,
});
} catch {
res.status(500).json({
error: "Failed to translate the text",
});
}
});
app.listen(PORT, HOST, () => {
console.log(`Server is running on http:${HOST}:${PORT}`);
});