-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
135 lines (120 loc) · 3.78 KB
/
server.ts
File metadata and controls
135 lines (120 loc) · 3.78 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import express from "express";
import cors from "cors";
import generateHandler from "./api/generate";
import imageHandler from "./api/image";
import modelsHandler from "./api/models";
import sharedBalanceHandler from "./api/sharedBalance";
import * as dotenv from "dotenv";
// Load environment variables from .env.local or .env
dotenv.config({ path: ".env.local" });
dotenv.config({ path: ".env" });
const app = express();
const PORT = process.env.API_PORT || 3001;
type VercelHandler = (
req: Parameters<typeof generateHandler>[0],
res: Parameters<typeof generateHandler>[1]
) => Promise<void> | void;
// Middleware
app.use(cors());
app.use(express.json());
const parseCookies = (
cookieHeader: string | string[] | undefined
): Record<string, string> => {
if (!cookieHeader) return {};
const raw = Array.isArray(cookieHeader) ? cookieHeader.join(";") : cookieHeader;
return raw.split(";").reduce<Record<string, string>>((acc, entry) => {
const separatorIndex = entry.indexOf("=");
if (separatorIndex <= 0) return acc;
const name = entry.slice(0, separatorIndex).trim();
const value = entry.slice(separatorIndex + 1).trim();
if (!name) return acc;
try {
acc[name] = decodeURIComponent(value);
} catch {
acc[name] = value;
}
return acc;
}, {});
};
// Convert Express request/response to Vercel format
const runVercelHandler = async (
req: express.Request,
res: express.Response,
handler: VercelHandler
) => {
// Create a Vercel-compatible request object
const vercelReq = {
method: req.method,
url: req.url,
headers: req.headers,
query: (req.query || {}) as Record<string, string | string[]>,
cookies: parseCookies(req.headers.cookie) as Record<string, string>,
body: req.body,
} as Parameters<typeof handler>[0];
// Create a Vercel-compatible response object
let statusCode = 200;
const vercelRes = {
status: (code: number) => {
statusCode = code;
res.status(code);
return vercelRes;
},
json: (body: unknown) => {
if (!res.headersSent) {
res.status(statusCode);
res.json(body);
}
},
// Add other methods that might be needed
setHeader: (name: string, value: string | string[]) => {
res.setHeader(name, value);
},
getHeader: (name: string) => {
return res.getHeader(name);
},
end: (chunk?: unknown) => {
if (!res.headersSent) {
res.status(statusCode);
}
res.end(chunk);
},
} as Parameters<typeof handler>[1];
try {
await handler(vercelReq, vercelRes);
} catch (error) {
console.error("Error handling request:", error);
if (!res.headersSent) {
res.status(500).json({
error: error instanceof Error ? error.message : "Internal server error",
});
}
}
};
app.post("/api/generate", async (req, res) => {
await runVercelHandler(req, res, generateHandler);
});
app.get("/api/models", async (req, res) => {
await runVercelHandler(req, res, modelsHandler);
});
app.get("/api/image", async (req, res) => {
await runVercelHandler(req, res, imageHandler);
});
app.get("/api/shared-balance", async (req, res) => {
await runVercelHandler(req, res, sharedBalanceHandler);
});
app.listen(PORT, () => {
console.log(`🚀 Local API server running on http://localhost:${PORT}`);
console.log(`📡 API endpoint: http://localhost:${PORT}/api/generate`);
console.log(`🧠 Model endpoint: http://localhost:${PORT}/api/models`);
console.log(`🖼️ Image endpoint: http://localhost:${PORT}/api/image`);
console.log(
`🌸 Shared balance endpoint: http://localhost:${PORT}/api/shared-balance`
);
console.log(
`🎨 POLLINATIONS_API_KEY: ${
process.env.POLLINATIONS_API_KEY
? `${process.env.POLLINATIONS_API_KEY.slice(0, 8)}...`
: "NOT SET"
}`
);
});