create-cellsweb-rpc-api 1.0.17 → 1.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
package/template/src/server.ts
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
* CellsWeb RPC API Server Entrypoint powered by @cellsweb/rpc-core
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import http from "node:http";
|
|
7
8
|
import { CoreRPC } from "@cellsweb/rpc-core";
|
|
8
9
|
import { env } from "./env";
|
|
10
|
+
import { storage } from "./utils/storage";
|
|
9
11
|
|
|
10
12
|
export const app = new CoreRPC({
|
|
11
13
|
functionsDir: "./src/functions",
|
|
@@ -15,4 +17,39 @@ export const app = new CoreRPC({
|
|
|
15
17
|
docs: true,
|
|
16
18
|
});
|
|
17
19
|
|
|
18
|
-
await app.
|
|
20
|
+
const rpcHandler = await app.createHandler();
|
|
21
|
+
|
|
22
|
+
const server = http.createServer(async (req, res) => {
|
|
23
|
+
const url = req.url ?? "/";
|
|
24
|
+
const method = req.method ?? "GET";
|
|
25
|
+
|
|
26
|
+
// ── Static Files Route (/uploads/*) ──
|
|
27
|
+
if (method === "GET" && url.startsWith("/uploads/")) {
|
|
28
|
+
const filePath = decodeURIComponent(url.replace(/^\/uploads\//, ""));
|
|
29
|
+
const result = await storage.serve(filePath);
|
|
30
|
+
if (!result) {
|
|
31
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
32
|
+
res.end(
|
|
33
|
+
JSON.stringify({
|
|
34
|
+
status: "error",
|
|
35
|
+
code: "not_found",
|
|
36
|
+
message: "File not found",
|
|
37
|
+
}),
|
|
38
|
+
);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
res.writeHead(200, {
|
|
42
|
+
"Content-Type": result.mimeType,
|
|
43
|
+
"Cache-Control": "public, max-age=86400",
|
|
44
|
+
});
|
|
45
|
+
res.end(result.buffer);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── Core RPC Engine Handler (Handles /rpc, /docs, /health) ──
|
|
50
|
+
await rpcHandler(req, res);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
server.listen(env.API_PORT, env.API_HOST, () => {
|
|
54
|
+
console.log(`Server listening at http://${env.API_HOST}:${env.API_PORT}`);
|
|
55
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* utils/imageHandler.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* Generic, domain-agnostic file & image processing utility.
|
|
5
|
+
* Works seamlessly with @cellsweb/rpc-core UploadedFile streams, custom buffers, or string URLs.
|
|
6
|
+
* Storage mode agnostic — works for both "local" disk and "s3" modes.
|
|
7
|
+
* Returns relative paths ("uploads/...") for local storage so database entries remain domain-agnostic.
|
|
8
|
+
*/
|
|
9
|
+
import { UploadedFile } from "@cellsweb/rpc-core";
|
|
10
|
+
import { storage, toRelativeImageUrl } from "./storage";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Process a single image/file field (UploadedFile instance, buffer object, or URL string).
|
|
14
|
+
* If a new UploadedFile is passed, uploads it to storage and deletes old file if replacing.
|
|
15
|
+
* Normalizes output into a domain-agnostic relative path for local storage.
|
|
16
|
+
*/
|
|
17
|
+
export async function processImageField(
|
|
18
|
+
imageInput: unknown,
|
|
19
|
+
dir: string = "general",
|
|
20
|
+
existingUrl?: string,
|
|
21
|
+
): Promise<string | undefined> {
|
|
22
|
+
if (!imageInput) return existingUrl ? toRelativeImageUrl(existingUrl) : undefined;
|
|
23
|
+
|
|
24
|
+
// 1. UploadedFile instance or custom object with toBuffer()
|
|
25
|
+
if (
|
|
26
|
+
imageInput instanceof UploadedFile ||
|
|
27
|
+
(typeof imageInput === "object" && imageInput !== null && "toBuffer" in imageInput)
|
|
28
|
+
) {
|
|
29
|
+
const file = imageInput as UploadedFile;
|
|
30
|
+
const buffer = await file.toBuffer();
|
|
31
|
+
const filename = file.filename || "upload.jpg";
|
|
32
|
+
const uploaded = await storage.upload(buffer, filename, dir);
|
|
33
|
+
|
|
34
|
+
// Delete existing old file if replacing
|
|
35
|
+
if (existingUrl && typeof existingUrl === "string") {
|
|
36
|
+
try {
|
|
37
|
+
await storage.delete(existingUrl);
|
|
38
|
+
} catch {
|
|
39
|
+
// Ignore delete errors if old file doesn't exist
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return toRelativeImageUrl(uploaded.url);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// 2. Existing URL string
|
|
46
|
+
if (typeof imageInput === "string") {
|
|
47
|
+
return toRelativeImageUrl(imageInput);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return existingUrl ? toRelativeImageUrl(existingUrl) : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Process multiple image/file fields for catalogs, galleries, or attachments.
|
|
55
|
+
* Handles removing deleted file URLs from storage and uploading new file objects.
|
|
56
|
+
* Normalizes output into domain-agnostic relative paths for local storage.
|
|
57
|
+
*/
|
|
58
|
+
export async function processMultipleImageFields(
|
|
59
|
+
imagesInput: unknown[],
|
|
60
|
+
dir: string = "gallery",
|
|
61
|
+
removeList: string[] = [],
|
|
62
|
+
): Promise<string[]> {
|
|
63
|
+
// 1. Delete files specified in removeList from storage
|
|
64
|
+
for (const url of removeList) {
|
|
65
|
+
if (url && typeof url === "string") {
|
|
66
|
+
try {
|
|
67
|
+
await storage.delete(url);
|
|
68
|
+
} catch {
|
|
69
|
+
// Ignore delete errors
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const finalUrls: string[] = [];
|
|
75
|
+
if (!Array.isArray(imagesInput)) return finalUrls;
|
|
76
|
+
|
|
77
|
+
for (const item of imagesInput) {
|
|
78
|
+
if (typeof item === "string") {
|
|
79
|
+
// Keep existing URL if it wasn't marked for removal
|
|
80
|
+
if (!removeList.includes(item)) {
|
|
81
|
+
finalUrls.push(toRelativeImageUrl(item));
|
|
82
|
+
}
|
|
83
|
+
} else if (
|
|
84
|
+
item instanceof UploadedFile ||
|
|
85
|
+
(typeof item === "object" && item !== null && "toBuffer" in item)
|
|
86
|
+
) {
|
|
87
|
+
const file = item as UploadedFile;
|
|
88
|
+
const buffer = await file.toBuffer();
|
|
89
|
+
const filename = file.filename || "upload.jpg";
|
|
90
|
+
const uploaded = await storage.upload(buffer, filename, dir);
|
|
91
|
+
finalUrls.push(toRelativeImageUrl(uploaded.url));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return finalUrls;
|
|
96
|
+
}
|
|
@@ -1,11 +1,199 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* utils/storage.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* Dual-mode file storage utility — supports "local" disk or "s3" (AWS / R2 / Wasabi / MinIO).
|
|
5
|
+
* Mode is selected via UPLOAD_MODE environment variable.
|
|
6
|
+
*/
|
|
7
|
+
|
|
2
8
|
import path from "node:path";
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import fs from "node:fs/promises";
|
|
3
11
|
import { env } from "../env";
|
|
4
12
|
|
|
13
|
+
export type StorageMode = "local" | "s3";
|
|
14
|
+
|
|
15
|
+
export interface UploadResult {
|
|
16
|
+
url: string; // Domain-agnostic relative URL (e.g. "uploads/products/filename.jpg")
|
|
17
|
+
fullUrl: string; // Absolute URL (prefixed with SERVER_URL or S3/R2 public URL)
|
|
18
|
+
path: string; // Relative storage path or S3 key (for deletion)
|
|
19
|
+
name: string; // Final sanitized filename
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Normalizes any image URL or path into a relative storage path (e.g. "uploads/products/filename.jpg").
|
|
24
|
+
* Domain-agnostic so database records never contain hardcoded IP/hostnames for local files.
|
|
25
|
+
* External S3/R2/CDN URLs are returned as-is.
|
|
26
|
+
*/
|
|
27
|
+
export function toRelativeImageUrl(pathOrUrl?: string | null): string {
|
|
28
|
+
if (!pathOrUrl || pathOrUrl === "-") return "";
|
|
29
|
+
if (typeof pathOrUrl !== "string") return "";
|
|
30
|
+
|
|
31
|
+
const trimmed = pathOrUrl.trim();
|
|
32
|
+
if (!trimmed || trimmed === "-") return "";
|
|
33
|
+
|
|
34
|
+
// If local uploads path (even from a previous IP/domain/SERVER_URL), convert to relative path
|
|
35
|
+
if (trimmed.includes("/uploads/")) {
|
|
36
|
+
const relPath = trimmed.split("/uploads/")[1];
|
|
37
|
+
return `uploads/${relPath.replace(/^\/+/, "")}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// If already relative uploads path
|
|
41
|
+
if (trimmed.startsWith("uploads/")) {
|
|
42
|
+
return trimmed;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// External S3 / R2 / CDN URL — return unchanged
|
|
46
|
+
return trimmed;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Resolves any relative path or full URL into a valid client-accessible URL.
|
|
51
|
+
* - If input is an external S3/R2/CDN URL, returns it unchanged.
|
|
52
|
+
* - If input is a relative local path or contains an old SERVER_URL /uploads/, rebinds it dynamically to current env.SERVER_URL.
|
|
53
|
+
*/
|
|
54
|
+
export function resolveImageUrl(pathOrUrl?: string | null): string {
|
|
55
|
+
if (!pathOrUrl || pathOrUrl === "-") return "";
|
|
56
|
+
|
|
57
|
+
const serverUrl = (env.SERVER_URL || "http://localhost:4000").replace(/\/$/, "");
|
|
58
|
+
|
|
59
|
+
// 1. If it points to local uploads path (even from a previous IP/domain), rebind to current SERVER_URL
|
|
60
|
+
if (pathOrUrl.includes("/uploads/")) {
|
|
61
|
+
const relPath = pathOrUrl.split("/uploads/")[1];
|
|
62
|
+
return `${serverUrl}/uploads/${relPath.replace(/^\/+/, "")}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 2. External HTTP/HTTPS URL (S3, R2, CDN)
|
|
66
|
+
if (/^https?:\/\//i.test(pathOrUrl)) {
|
|
67
|
+
return pathOrUrl;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 3. Relative path (e.g. "uploads/products/image.jpg" or "products/image.jpg")
|
|
71
|
+
let clean = pathOrUrl.replace(/^\/+/, "");
|
|
72
|
+
if (!clean.startsWith("uploads/")) {
|
|
73
|
+
clean = `uploads/${clean}`;
|
|
74
|
+
}
|
|
75
|
+
return `${serverUrl}/${clean}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ─── Sanitize filename ────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
function sanitizeFilename(original: string): string {
|
|
81
|
+
const ext = path.extname(original);
|
|
82
|
+
const base = path.basename(original, ext).replace(/[^a-z0-9._-]/gi, "_");
|
|
83
|
+
const timestamp = Date.now();
|
|
84
|
+
const rand = Math.random().toString(36).substring(2, 8);
|
|
85
|
+
return `${base}_${timestamp}_${rand}${ext}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ─── Local storage ────────────────────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
function getUploadRoot(): string {
|
|
91
|
+
const configured = env.UPLOAD_DIR || "public/uploads";
|
|
92
|
+
return path.isAbsolute(configured)
|
|
93
|
+
? configured
|
|
94
|
+
: path.resolve(process.cwd(), configured);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function cleanStoragePath(inputPath: string): string {
|
|
98
|
+
let p = inputPath;
|
|
99
|
+
try {
|
|
100
|
+
p = decodeURIComponent(p);
|
|
101
|
+
} catch {}
|
|
102
|
+
|
|
103
|
+
const serverUrl = (env.SERVER_URL || "http://localhost:4000").replace(/\/$/, "");
|
|
104
|
+
|
|
105
|
+
if (p.startsWith(serverUrl)) {
|
|
106
|
+
p = p.substring(serverUrl.length);
|
|
107
|
+
} else {
|
|
108
|
+
p = p.replace(/^https?:\/\/[^/]+/i, "");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
p = p.split("?")[0].split("#")[0];
|
|
112
|
+
p = p.replace(/\\/g, "/");
|
|
113
|
+
|
|
114
|
+
while (/^\/?(uploads?\/|\/)/i.test(p)) {
|
|
115
|
+
p = p.replace(/^\/?(uploads?\/|\/)/i, "");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return p;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function localUpload(
|
|
122
|
+
buffer: Buffer,
|
|
123
|
+
originalName: string,
|
|
124
|
+
dir: string = "",
|
|
125
|
+
): Promise<UploadResult> {
|
|
126
|
+
const uploadRoot = getUploadRoot();
|
|
127
|
+
const safeName = sanitizeFilename(originalName);
|
|
128
|
+
const relDir = dir.replace(/^\/+/, "");
|
|
129
|
+
const savePath = path.join(uploadRoot, relDir, safeName);
|
|
130
|
+
const dirPath = path.dirname(savePath);
|
|
131
|
+
|
|
132
|
+
await fs.mkdir(dirPath, { recursive: true });
|
|
133
|
+
await fs.writeFile(savePath, buffer);
|
|
134
|
+
|
|
135
|
+
const relativePath = relDir ? `${relDir}/${safeName}` : safeName;
|
|
136
|
+
const normalizedRelPath = relativePath.replace(/\\/g, "/");
|
|
137
|
+
const relUrl = `uploads/${normalizedRelPath}`;
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
url: relUrl,
|
|
141
|
+
fullUrl: resolveImageUrl(relUrl),
|
|
142
|
+
path: normalizedRelPath,
|
|
143
|
+
name: safeName,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function localDelete(relativePath: string): Promise<boolean> {
|
|
148
|
+
try {
|
|
149
|
+
const uploadRoot = getUploadRoot();
|
|
150
|
+
const clean = cleanStoragePath(relativePath);
|
|
151
|
+
const fullPath = path.join(uploadRoot, clean);
|
|
152
|
+
const resolved = path.resolve(fullPath);
|
|
153
|
+
const root = path.resolve(uploadRoot);
|
|
154
|
+
|
|
155
|
+
// Security: prevent directory traversal
|
|
156
|
+
if (!resolved.startsWith(root)) {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (existsSync(fullPath)) {
|
|
161
|
+
await fs.unlink(fullPath);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
} catch {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function localServe(relativePath: string): Promise<{ buffer: Buffer; mimeType: string } | null> {
|
|
171
|
+
try {
|
|
172
|
+
const { default: mime } = await import("mime-types");
|
|
173
|
+
const uploadRoot = getUploadRoot();
|
|
174
|
+
const clean = cleanStoragePath(relativePath);
|
|
175
|
+
|
|
176
|
+
const fullPath = path.join(uploadRoot, clean);
|
|
177
|
+
|
|
178
|
+
const resolved = path.resolve(fullPath);
|
|
179
|
+
const root = path.resolve(uploadRoot);
|
|
180
|
+
if (!resolved.startsWith(root)) return null;
|
|
181
|
+
if (!existsSync(fullPath)) return null;
|
|
182
|
+
|
|
183
|
+
const buffer = await fs.readFile(fullPath);
|
|
184
|
+
const mimeType = mime.lookup(fullPath) || "application/octet-stream";
|
|
185
|
+
return { buffer, mimeType };
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ─── S3 Storage Integration (@aws-sdk/client-s3) ─────────────────────────────
|
|
192
|
+
|
|
5
193
|
let s3ClientInstance: any = null;
|
|
6
194
|
|
|
7
195
|
async function getS3Client() {
|
|
8
|
-
if (s3ClientInstance) return s3ClientInstance;
|
|
196
|
+
if (s3ClientInstance) return { s3: s3ClientInstance, bucket: env.S3_BUCKET! };
|
|
9
197
|
|
|
10
198
|
if (!env.S3_BUCKET || !env.S3_REGION || !env.S3_ACCESS_KEY || !env.S3_SECRET_KEY) {
|
|
11
199
|
throw new Error(
|
|
@@ -14,7 +202,6 @@ async function getS3Client() {
|
|
|
14
202
|
}
|
|
15
203
|
|
|
16
204
|
try {
|
|
17
|
-
// Dynamic import allows optional usage without forcing heavy SDK load if local mode is used
|
|
18
205
|
const { S3Client } = await import("@aws-sdk/client-s3");
|
|
19
206
|
s3ClientInstance = new S3Client({
|
|
20
207
|
region: env.S3_REGION,
|
|
@@ -24,7 +211,7 @@ async function getS3Client() {
|
|
|
24
211
|
},
|
|
25
212
|
...(env.S3_ENDPOINT ? { endpoint: env.S3_ENDPOINT, forcePathStyle: true } : {}),
|
|
26
213
|
});
|
|
27
|
-
return s3ClientInstance;
|
|
214
|
+
return { s3: s3ClientInstance, bucket: env.S3_BUCKET };
|
|
28
215
|
} catch {
|
|
29
216
|
throw new Error(
|
|
30
217
|
"S3 upload failed: @aws-sdk/client-s3 package is not installed. Run `pnpm add @aws-sdk/client-s3` to enable S3 storage.",
|
|
@@ -32,102 +219,118 @@ async function getS3Client() {
|
|
|
32
219
|
}
|
|
33
220
|
}
|
|
34
221
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
if (mode === "s3") {
|
|
44
|
-
const client = await getS3Client();
|
|
45
|
-
const { PutObjectCommand } = await import("@aws-sdk/client-s3");
|
|
46
|
-
const key = subDir ? `${subDir.replace(/^\/|\/$/g, "")}/${uniqueFileName}` : uniqueFileName;
|
|
47
|
-
|
|
48
|
-
await client.send(
|
|
49
|
-
new PutObjectCommand({
|
|
50
|
-
Bucket: env.S3_BUCKET,
|
|
51
|
-
Key: key,
|
|
52
|
-
Body: buffer,
|
|
53
|
-
}),
|
|
54
|
-
);
|
|
55
|
-
|
|
56
|
-
const url = env.S3_ENDPOINT
|
|
57
|
-
? `${env.S3_ENDPOINT.replace(/\/$/, "")}/${env.S3_BUCKET}/${key}`
|
|
58
|
-
: `https://${env.S3_BUCKET}.s3.${env.S3_REGION}.amazonaws.com/${key}`;
|
|
59
|
-
|
|
60
|
-
return { url, path: key };
|
|
61
|
-
}
|
|
222
|
+
async function s3Upload(
|
|
223
|
+
buffer: Buffer,
|
|
224
|
+
originalName: string,
|
|
225
|
+
dir: string = "",
|
|
226
|
+
): Promise<UploadResult> {
|
|
227
|
+
const { default: mime } = await import("mime-types");
|
|
228
|
+
const { s3, bucket } = await getS3Client();
|
|
229
|
+
const { PutObjectCommand } = await import("@aws-sdk/client-s3");
|
|
62
230
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
await fs.promises.writeFile(filePath, buffer);
|
|
69
|
-
|
|
70
|
-
const relativeUrlPath = path.join("/uploads", subDir, uniqueFileName).replace(/\\/g, "/");
|
|
71
|
-
const url = `${env.SERVER_URL}${relativeUrlPath}`;
|
|
72
|
-
|
|
73
|
-
return { url, path: filePath };
|
|
74
|
-
},
|
|
75
|
-
|
|
76
|
-
async delete(filePathOrKey: string): Promise<boolean> {
|
|
77
|
-
const mode = env.UPLOAD_MODE ?? "local";
|
|
78
|
-
|
|
79
|
-
if (mode === "s3") {
|
|
80
|
-
try {
|
|
81
|
-
const client = await getS3Client();
|
|
82
|
-
const { DeleteObjectCommand } = await import("@aws-sdk/client-s3");
|
|
83
|
-
await client.send(
|
|
84
|
-
new DeleteObjectCommand({
|
|
85
|
-
Bucket: env.S3_BUCKET,
|
|
86
|
-
Key: filePathOrKey,
|
|
87
|
-
}),
|
|
88
|
-
);
|
|
89
|
-
return true;
|
|
90
|
-
} catch {
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
231
|
+
const safeName = sanitizeFilename(originalName);
|
|
232
|
+
const relDir = dir.replace(/^\/+/, "");
|
|
233
|
+
const key = relDir ? `${relDir}/${safeName}` : safeName;
|
|
234
|
+
const contentType = mime.lookup(originalName) || "application/octet-stream";
|
|
94
235
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
236
|
+
await s3.send(
|
|
237
|
+
new PutObjectCommand({
|
|
238
|
+
Bucket: bucket,
|
|
239
|
+
Key: key,
|
|
240
|
+
Body: buffer,
|
|
241
|
+
ContentType: contentType,
|
|
242
|
+
}),
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
let publicUrl = "";
|
|
246
|
+
if (env.S3_ENDPOINT) {
|
|
247
|
+
const baseEndpoint = env.S3_ENDPOINT.replace(/\/$/, "");
|
|
248
|
+
publicUrl = `${baseEndpoint}/${bucket}/${key}`;
|
|
249
|
+
} else {
|
|
250
|
+
const region = env.S3_REGION || "us-east-1";
|
|
251
|
+
publicUrl = `https://${bucket}.s3.${region}.amazonaws.com/${key}`;
|
|
252
|
+
}
|
|
102
253
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
254
|
+
return {
|
|
255
|
+
url: publicUrl,
|
|
256
|
+
fullUrl: publicUrl,
|
|
257
|
+
path: key,
|
|
258
|
+
name: safeName,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
106
261
|
|
|
107
|
-
|
|
108
|
-
|
|
262
|
+
async function s3Delete(relativePath: string): Promise<boolean> {
|
|
263
|
+
try {
|
|
264
|
+
const { s3, bucket } = await getS3Client();
|
|
265
|
+
const { DeleteObjectCommand } = await import("@aws-sdk/client-s3");
|
|
266
|
+
const cleanKey = cleanStoragePath(relativePath);
|
|
109
267
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
268
|
+
await s3.send(
|
|
269
|
+
new DeleteObjectCommand({
|
|
270
|
+
Bucket: bucket,
|
|
271
|
+
Key: cleanKey,
|
|
272
|
+
}),
|
|
273
|
+
);
|
|
274
|
+
return true;
|
|
275
|
+
} catch {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function s3Serve(relativePath: string): Promise<{ buffer: Buffer; mimeType: string } | null> {
|
|
281
|
+
try {
|
|
282
|
+
const { default: mime } = await import("mime-types");
|
|
283
|
+
const { s3, bucket } = await getS3Client();
|
|
284
|
+
const { GetObjectCommand } = await import("@aws-sdk/client-s3");
|
|
285
|
+
const cleanKey = cleanStoragePath(relativePath);
|
|
286
|
+
|
|
287
|
+
const res = await s3.send(
|
|
288
|
+
new GetObjectCommand({
|
|
289
|
+
Bucket: bucket,
|
|
290
|
+
Key: cleanKey,
|
|
291
|
+
}),
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
if (!res.Body) return null;
|
|
295
|
+
const byteArray = await res.Body.transformToByteArray();
|
|
296
|
+
const buffer = Buffer.from(byteArray);
|
|
297
|
+
const mimeType = res.ContentType || mime.lookup(cleanKey) || "application/octet-stream";
|
|
298
|
+
return { buffer, mimeType };
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
113
303
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
} catch {
|
|
130
|
-
return null;
|
|
304
|
+
// ─── Dynamic .gitignore Initialization for Local Mode ─────────────────────────
|
|
305
|
+
|
|
306
|
+
const mode: StorageMode = (env.UPLOAD_MODE || "local") as StorageMode;
|
|
307
|
+
|
|
308
|
+
async function ensureStorageGitignore(): Promise<void> {
|
|
309
|
+
if (mode !== "local") return;
|
|
310
|
+
|
|
311
|
+
try {
|
|
312
|
+
const uploadRoot = getUploadRoot();
|
|
313
|
+
await fs.mkdir(uploadRoot, { recursive: true });
|
|
314
|
+
|
|
315
|
+
const gitignorePath = path.join(uploadRoot, ".gitignore");
|
|
316
|
+
if (!existsSync(gitignorePath)) {
|
|
317
|
+
const gitignoreContent = `# Ignore all uploaded media files in this directory\n*\n!.gitignore\n`;
|
|
318
|
+
await fs.writeFile(gitignorePath, gitignoreContent, "utf8");
|
|
131
319
|
}
|
|
132
|
-
}
|
|
320
|
+
} catch {}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
ensureStorageGitignore().catch(() => {});
|
|
324
|
+
|
|
325
|
+
export const storage = {
|
|
326
|
+
mode,
|
|
327
|
+
|
|
328
|
+
upload: (buffer: Buffer, originalName: string, dir: string = "") =>
|
|
329
|
+
mode === "s3" ? s3Upload(buffer, originalName, dir) : localUpload(buffer, originalName, dir),
|
|
330
|
+
|
|
331
|
+
delete: (relativePath: string) =>
|
|
332
|
+
mode === "s3" ? s3Delete(relativePath) : localDelete(relativePath),
|
|
333
|
+
|
|
334
|
+
serve: (relativePath: string) =>
|
|
335
|
+
mode === "s3" ? s3Serve(relativePath) : localServe(relativePath),
|
|
133
336
|
};
|