create-cellsweb-rpc-api 1.0.0
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/README.md +33 -0
- package/bin/create.js +232 -0
- package/package.json +30 -0
- package/template/.env.example +25 -0
- package/template/README.md +116 -0
- package/template/nodemon.json +7 -0
- package/template/scripts/create-function.ts +423 -0
- package/template/scripts/create-middleware.ts +174 -0
- package/template/scripts/tsconfig.json +18 -0
- package/template/src/env.ts +79 -0
- package/template/src/functions/.gitkeep +0 -0
- package/template/src/functions/public/hello/constants.ts +26 -0
- package/template/src/functions/public/hello/middlewares.ts +5 -0
- package/template/src/functions/public/hello/run.ts +21 -0
- package/template/src/functions/public/hello/test.ts +9 -0
- package/template/src/middlewares/auth/constants.ts +39 -0
- package/template/src/middlewares/auth/run.ts +73 -0
- package/template/src/middlewares/auth/test.ts +23 -0
- package/template/src/middlewares/rateLimit/constants.ts +11 -0
- package/template/src/middlewares/rateLimit/run.ts +61 -0
- package/template/src/middlewares/rateLimit/test.ts +23 -0
- package/template/src/server.ts +28 -0
- package/template/src/telemetry.ts +58 -0
- package/template/src/utils/storage.ts +133 -0
- package/template/test.ts +265 -0
- package/template/vitest.config.ts +14 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* functions/public/hello/constants.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* SCHEMA & CONTRACT DEFINITION
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { Type } from "@sinclair/typebox";
|
|
8
|
+
|
|
9
|
+
export const metadata = {
|
|
10
|
+
description: "Sample hello JSON RPC function",
|
|
11
|
+
isPublic: true,
|
|
12
|
+
deprecated: false,
|
|
13
|
+
tags: ["sample"],
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export const contentType = "application/json" as const;
|
|
17
|
+
|
|
18
|
+
export const headersSchema = Type.Object({}, { additionalProperties: true });
|
|
19
|
+
|
|
20
|
+
export const inputSchema = Type.Object({
|
|
21
|
+
name: Type.String({ minLength: 1, description: "Your name" }),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export const outputSchema = Type.Object({
|
|
25
|
+
greeting: Type.String(),
|
|
26
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* functions/public/hello/run.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* BUSINESS LOGIC HANDLER
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Static } from "@sinclair/typebox";
|
|
8
|
+
import type { MiddlewareContext } from "@cellsweb/rpc-core";
|
|
9
|
+
import { inputSchema, outputSchema } from "./constants";
|
|
10
|
+
|
|
11
|
+
type Input = Static<typeof inputSchema>;
|
|
12
|
+
type Output = Static<typeof outputSchema>;
|
|
13
|
+
|
|
14
|
+
export const run = async (
|
|
15
|
+
input: Input,
|
|
16
|
+
_context: MiddlewareContext,
|
|
17
|
+
): Promise<Output> => {
|
|
18
|
+
return {
|
|
19
|
+
greeting: `Hello, ${input.name}!`,
|
|
20
|
+
};
|
|
21
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { run } from "./run";
|
|
3
|
+
|
|
4
|
+
describe("public.hello", () => {
|
|
5
|
+
it("returns greeting", async () => {
|
|
6
|
+
const result = await run({ name: "Alice" }, {} as any);
|
|
7
|
+
expect(result.greeting).toBe("Hello, Alice!");
|
|
8
|
+
});
|
|
9
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
|
|
3
|
+
export type UserRole = "user" | "admin" | "staff" | "vendor" | "dev";
|
|
4
|
+
|
|
5
|
+
export const metadata = {
|
|
6
|
+
name: "auth",
|
|
7
|
+
description: "Validates the bearer token and injects auth claims into context",
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const headersSchema = Type.Object({
|
|
11
|
+
authorization: Type.Optional(Type.String()),
|
|
12
|
+
token: Type.Optional(Type.String()),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const optionsSchema = Type.Object({
|
|
16
|
+
roles: Type.Optional(
|
|
17
|
+
Type.Array(
|
|
18
|
+
Type.Union([
|
|
19
|
+
Type.Literal("user"),
|
|
20
|
+
Type.Literal("admin"),
|
|
21
|
+
Type.Literal("vendor"),
|
|
22
|
+
Type.Literal("staff"),
|
|
23
|
+
Type.Literal("dev"),
|
|
24
|
+
]),
|
|
25
|
+
),
|
|
26
|
+
),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
export const outputSchema = Type.Object({
|
|
30
|
+
userId: Type.String(),
|
|
31
|
+
role: Type.Union([
|
|
32
|
+
Type.Literal("user"),
|
|
33
|
+
Type.Literal("admin"),
|
|
34
|
+
Type.Literal("vendor"),
|
|
35
|
+
Type.Literal("staff"),
|
|
36
|
+
Type.Literal("dev"),
|
|
37
|
+
]),
|
|
38
|
+
user: Type.Record(Type.String(), Type.Unknown()),
|
|
39
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/middlewares/auth/run.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* PRE-SCAFFOLDED AUTHENTICATION MIDDLEWARE
|
|
5
|
+
*
|
|
6
|
+
* HOW TO USE & CUSTOMIZE THIS MIDDLEWARE:
|
|
7
|
+
* 1. Replace `verifyToken()` stub below with your JWT (jose/jsonwebtoken), database query, or OAuth logic.
|
|
8
|
+
* 2. Function declarations in `middlewares.ts` can pass options:
|
|
9
|
+
* `{ name: "auth", options: { roles: ["admin", "user"] } }`
|
|
10
|
+
* 3. In function `run.ts`, access authenticated user via `context.auth.user`.
|
|
11
|
+
* 4. Feel free to edit, rename, or delete this middleware if your project uses custom auth!
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Static } from "@sinclair/typebox";
|
|
15
|
+
import { AppError, ErrorCode, type MiddlewareFn } from "@cellsweb/rpc-core";
|
|
16
|
+
import { optionsSchema, outputSchema, type UserRole } from "./constants";
|
|
17
|
+
|
|
18
|
+
export type AuthOptions = Static<typeof optionsSchema>;
|
|
19
|
+
export type AuthContext = Static<typeof outputSchema>;
|
|
20
|
+
|
|
21
|
+
interface IUser {
|
|
22
|
+
_id: unknown;
|
|
23
|
+
role: UserRole;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// TODO: Replace this stub with your real JWT/database user verification logic!
|
|
28
|
+
async function verifyToken(_token: string | undefined): Promise<IUser | null> {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const run: MiddlewareFn<AuthOptions, { auth?: AuthContext }> = async (
|
|
33
|
+
{ headers, options },
|
|
34
|
+
context,
|
|
35
|
+
) => {
|
|
36
|
+
const authHeader =
|
|
37
|
+
(Array.isArray(headers["authorization"]) ? headers["authorization"][0] : headers["authorization"]) ??
|
|
38
|
+
(Array.isArray(headers["token"]) ? headers["token"][0] : headers["token"]);
|
|
39
|
+
|
|
40
|
+
const token = (typeof authHeader === "string" ? authHeader : "")?.replace(/^Bearer\s+/i, "") ?? undefined;
|
|
41
|
+
const roles = options.roles ?? [];
|
|
42
|
+
const isRolesEmpty = roles.length === 0;
|
|
43
|
+
|
|
44
|
+
let user: IUser | null = null;
|
|
45
|
+
try {
|
|
46
|
+
user = await verifyToken(token);
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (err instanceof AppError) throw err;
|
|
49
|
+
throw new AppError(ErrorCode.UNAUTHORIZED, "Invalid or expired token");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (!isRolesEmpty) {
|
|
53
|
+
if (!user) {
|
|
54
|
+
throw new AppError(ErrorCode.UNAUTHORIZED, "Authentication required");
|
|
55
|
+
}
|
|
56
|
+
if (!roles.includes(user.role)) {
|
|
57
|
+
throw new AppError(ErrorCode.FORBIDDEN, "Insufficient permissions");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (user) {
|
|
62
|
+
return {
|
|
63
|
+
...context,
|
|
64
|
+
auth: {
|
|
65
|
+
userId: String(user._id),
|
|
66
|
+
role: user.role,
|
|
67
|
+
user: user as Record<string, unknown>,
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return context;
|
|
73
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { run } from "./run";
|
|
3
|
+
|
|
4
|
+
describe("middleware: auth", () => {
|
|
5
|
+
it("allows unauthenticated requests when no roles are required", async () => {
|
|
6
|
+
const ctx = await run(
|
|
7
|
+
{
|
|
8
|
+
headers: {},
|
|
9
|
+
options: { roles: [] },
|
|
10
|
+
function: {
|
|
11
|
+
key: "public.hello",
|
|
12
|
+
namespace: "public",
|
|
13
|
+
functionName: "hello",
|
|
14
|
+
metadata: {},
|
|
15
|
+
contentType: "application/json",
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
{ requestId: "req_1", ip: "127.0.0.1" } as any,
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
expect(ctx.requestId).toBe("req_1");
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
|
|
3
|
+
export const metadata = {
|
|
4
|
+
name: "rateLimit",
|
|
5
|
+
description: "Enforces per-function rate limits keyed on IP + namespace + functionName",
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export const optionsSchema = Type.Object({
|
|
9
|
+
windowSeconds: Type.Number({ minimum: 1, default: 60 }),
|
|
10
|
+
maxRequests: Type.Number({ minimum: 1, default: 100 }),
|
|
11
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/middlewares/rateLimit/run.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* PRE-SCAFFOLDED RATE LIMITING MIDDLEWARE
|
|
5
|
+
*
|
|
6
|
+
* HOW TO USE & CUSTOMIZE THIS MIDDLEWARE:
|
|
7
|
+
* 1. Uses RateLimiterMemory (in-memory) by default.
|
|
8
|
+
* 2. For multi-instance cluster production setups, swap `RateLimiterMemory` with `RateLimiterRedis`.
|
|
9
|
+
* 3. Function declarations in `middlewares.ts` specify limits:
|
|
10
|
+
* `{ name: "rateLimit", options: { windowSeconds: 60, maxRequests: 100 } }`
|
|
11
|
+
* 4. Feel free to edit, customize, or delete this middleware as needed!
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Static } from "@sinclair/typebox";
|
|
15
|
+
import { AppError, ErrorCode, type MiddlewareFn } from "@cellsweb/rpc-core";
|
|
16
|
+
import { LRUCache } from "lru-cache";
|
|
17
|
+
import { RateLimiterAbstract, RateLimiterMemory } from "rate-limiter-flexible";
|
|
18
|
+
import { optionsSchema } from "./constants";
|
|
19
|
+
|
|
20
|
+
type Options = Static<typeof optionsSchema>;
|
|
21
|
+
|
|
22
|
+
const limiterCache = new LRUCache<string, RateLimiterAbstract>({
|
|
23
|
+
max: 256,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function getOrCreateLimiter(
|
|
27
|
+
windowSeconds: number,
|
|
28
|
+
maxRequests: number,
|
|
29
|
+
): RateLimiterAbstract {
|
|
30
|
+
const key = `${windowSeconds}:${maxRequests}`;
|
|
31
|
+
let limiter = limiterCache.get(key);
|
|
32
|
+
|
|
33
|
+
if (!limiter) {
|
|
34
|
+
limiter = new RateLimiterMemory({
|
|
35
|
+
duration: windowSeconds,
|
|
36
|
+
points: maxRequests,
|
|
37
|
+
});
|
|
38
|
+
limiterCache.set(key, limiter);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return limiter;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const run: MiddlewareFn<Options> = async ({ options, function: fn }, context) => {
|
|
45
|
+
const { windowSeconds, maxRequests } = options;
|
|
46
|
+
const { ip, namespace, functionName } = context;
|
|
47
|
+
|
|
48
|
+
const limiter = getOrCreateLimiter(windowSeconds, maxRequests);
|
|
49
|
+
const rateLimitKey = `${ip}:${namespace}:${functionName}`;
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
await limiter.consume(rateLimitKey, 1);
|
|
53
|
+
} catch {
|
|
54
|
+
throw new AppError(
|
|
55
|
+
ErrorCode.RATE_LIMITED,
|
|
56
|
+
`Rate limit exceeded for ${namespace}.${functionName}. Maximum ${maxRequests} requests per ${windowSeconds}s.`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return context;
|
|
61
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { run } from "./run";
|
|
3
|
+
|
|
4
|
+
describe("middleware: rateLimit", () => {
|
|
5
|
+
it("consumes rate limit points without error", async () => {
|
|
6
|
+
const ctx = await run(
|
|
7
|
+
{
|
|
8
|
+
headers: {},
|
|
9
|
+
options: { windowSeconds: 60, maxRequests: 100 },
|
|
10
|
+
function: {
|
|
11
|
+
key: "public.hello",
|
|
12
|
+
namespace: "public",
|
|
13
|
+
functionName: "hello",
|
|
14
|
+
metadata: {},
|
|
15
|
+
contentType: "application/json",
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
{ requestId: "req_1", ip: "127.0.0.1", namespace: "public", functionName: "hello" } as any,
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
expect(ctx.requestId).toBe("req_1");
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* server.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* CellsWeb RPC API Server Entrypoint powered by @cellsweb/rpc-core
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import "./env";
|
|
8
|
+
import { CoreRPC } from "@cellsweb/rpc-core";
|
|
9
|
+
import { env } from "./env";
|
|
10
|
+
|
|
11
|
+
export const app = new CoreRPC({
|
|
12
|
+
functionsDir: "./src/functions",
|
|
13
|
+
middlewaresDir: "./src/middlewares",
|
|
14
|
+
port: env.API_PORT,
|
|
15
|
+
host: env.API_HOST,
|
|
16
|
+
docs: true,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export async function start(): Promise<void> {
|
|
20
|
+
await app.start();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (typeof require !== "undefined" && require.main === module) {
|
|
24
|
+
start().catch((err) => {
|
|
25
|
+
console.error("Startup error:", err);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* telemetry.ts
|
|
3
|
+
* ─────────────────────────────────────────────────────────────────────────────
|
|
4
|
+
* Optional Telemetry & Error Tracking integration (Sentry / Metrics).
|
|
5
|
+
*
|
|
6
|
+
* Sentry error reporting initializes automatically ONLY if SENTRY_DSN is configured
|
|
7
|
+
* in .env. Otherwise, errors are handled via pino logger with zero extra overhead.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { logger } from "@cellsweb/rpc-core";
|
|
11
|
+
import { env } from "./env";
|
|
12
|
+
|
|
13
|
+
let isSentryInitialized = false;
|
|
14
|
+
|
|
15
|
+
async function initSentry() {
|
|
16
|
+
if (isSentryInitialized) return;
|
|
17
|
+
if (!env.SENTRY_DSN) return;
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
const Sentry = await import("@sentry/node");
|
|
21
|
+
Sentry.init({
|
|
22
|
+
dsn: env.SENTRY_DSN,
|
|
23
|
+
environment: env.NODE_ENV,
|
|
24
|
+
enabled: env.TELEMETRY_ENABLED ?? true,
|
|
25
|
+
});
|
|
26
|
+
isSentryInitialized = true;
|
|
27
|
+
logger.info("Sentry error tracking initialized");
|
|
28
|
+
} catch {
|
|
29
|
+
logger.warn("Sentry DSN provided, but @sentry/node is not installed. Run `pnpm add @sentry/node` to enable.");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Auto-initialize Sentry if DSN is provided
|
|
34
|
+
initSentry().catch(() => {});
|
|
35
|
+
|
|
36
|
+
export const telemetry = {
|
|
37
|
+
/**
|
|
38
|
+
* Reports internal exceptions to Sentry (if configured) and logs via Pino.
|
|
39
|
+
*/
|
|
40
|
+
async captureException(error: unknown, contextData?: Record<string, unknown>): Promise<void> {
|
|
41
|
+
if (env.SENTRY_DSN) {
|
|
42
|
+
try {
|
|
43
|
+
const Sentry = await import("@sentry/node");
|
|
44
|
+
Sentry.captureException(error, { extra: contextData });
|
|
45
|
+
} catch {
|
|
46
|
+
// Fallback silently if Sentry package is not installed
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Records execution metrics or custom timing stats.
|
|
53
|
+
*/
|
|
54
|
+
recordMetric(metricName: string, value: number, tags?: Record<string, string>): void {
|
|
55
|
+
if (env.TELEMETRY_ENABLED === false) return;
|
|
56
|
+
logger.debug({ metricName, value, ...tags }, "Telemetry metric recorded");
|
|
57
|
+
},
|
|
58
|
+
};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { env } from "../env";
|
|
4
|
+
|
|
5
|
+
let s3ClientInstance: any = null;
|
|
6
|
+
|
|
7
|
+
async function getS3Client() {
|
|
8
|
+
if (s3ClientInstance) return s3ClientInstance;
|
|
9
|
+
|
|
10
|
+
if (!env.S3_BUCKET || !env.S3_REGION || !env.S3_ACCESS_KEY || !env.S3_SECRET_KEY) {
|
|
11
|
+
throw new Error(
|
|
12
|
+
"S3 upload failed: Missing required S3 environment variables (S3_BUCKET, S3_REGION, S3_ACCESS_KEY, S3_SECRET_KEY).",
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
// Dynamic import allows optional usage without forcing heavy SDK load if local mode is used
|
|
18
|
+
const { S3Client } = await import("@aws-sdk/client-s3");
|
|
19
|
+
s3ClientInstance = new S3Client({
|
|
20
|
+
region: env.S3_REGION,
|
|
21
|
+
credentials: {
|
|
22
|
+
accessKeyId: env.S3_ACCESS_KEY,
|
|
23
|
+
secretAccessKey: env.S3_SECRET_KEY,
|
|
24
|
+
},
|
|
25
|
+
...(env.S3_ENDPOINT ? { endpoint: env.S3_ENDPOINT, forcePathStyle: true } : {}),
|
|
26
|
+
});
|
|
27
|
+
return s3ClientInstance;
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"S3 upload failed: @aws-sdk/client-s3 package is not installed. Run `pnpm add @aws-sdk/client-s3` to enable S3 storage.",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const storage = {
|
|
36
|
+
async upload(buffer: Buffer, originalName: string, subDir = ""): Promise<{ url: string; path: string }> {
|
|
37
|
+
const mode = env.UPLOAD_MODE ?? "local";
|
|
38
|
+
|
|
39
|
+
const ext = path.extname(originalName);
|
|
40
|
+
const baseName = path.basename(originalName, ext).replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
41
|
+
const uniqueFileName = `${baseName}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}${ext}`;
|
|
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
|
+
}
|
|
62
|
+
|
|
63
|
+
// Local mode
|
|
64
|
+
const uploadDir = path.resolve(process.cwd(), env.UPLOAD_DIR ?? "public/uploads", subDir);
|
|
65
|
+
await fs.promises.mkdir(uploadDir, { recursive: true });
|
|
66
|
+
const filePath = path.join(uploadDir, uniqueFileName);
|
|
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
|
+
}
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
await fs.promises.unlink(filePathOrKey);
|
|
97
|
+
return true;
|
|
98
|
+
} catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
async serve(relativePath: string): Promise<{ stream: fs.ReadStream; mimeType: string } | null> {
|
|
104
|
+
const mode = env.UPLOAD_MODE ?? "local";
|
|
105
|
+
if (mode !== "local") return null;
|
|
106
|
+
|
|
107
|
+
const baseUploadDir = path.resolve(process.cwd(), env.UPLOAD_DIR ?? "public/uploads");
|
|
108
|
+
const fullPath = path.resolve(baseUploadDir, relativePath);
|
|
109
|
+
|
|
110
|
+
if (!fullPath.startsWith(baseUploadDir)) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
const stat = await fs.promises.stat(fullPath);
|
|
116
|
+
if (!stat.isFile()) return null;
|
|
117
|
+
|
|
118
|
+
const ext = path.extname(fullPath).toLowerCase();
|
|
119
|
+
let mimeType = "application/octet-stream";
|
|
120
|
+
if (ext === ".jpg" || ext === ".jpeg") mimeType = "image/jpeg";
|
|
121
|
+
else if (ext === ".png") mimeType = "image/png";
|
|
122
|
+
else if (ext === ".gif") mimeType = "image/gif";
|
|
123
|
+
else if (ext === ".webp") mimeType = "image/webp";
|
|
124
|
+
else if (ext === ".pdf") mimeType = "application/pdf";
|
|
125
|
+
else if (ext === ".json") mimeType = "application/json";
|
|
126
|
+
|
|
127
|
+
const stream = fs.createReadStream(fullPath);
|
|
128
|
+
return { stream, mimeType };
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
};
|