mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat(api): add generic tool route factory for all image tools
- createToolRoute<T> factory: handles multipart parsing, file validation, Zod settings validation, workspace management, and error handling - Each tool only needs to provide toolId, settingsSchema, and process function - Registers POST /api/v1/tools/:toolId routes automatically - Tool registry stub at routes/tools/index.ts ready for tool implementations - Catches Sharp errors and returns clean API error envelopes (422)
This commit is contained in:
@@ -11,6 +11,7 @@ import { registerUpload } from "./plugins/upload.js";
|
||||
import { registerStatic } from "./plugins/static.js";
|
||||
import { startCleanupCron } from "./lib/cleanup.js";
|
||||
import { fileRoutes } from "./routes/files.js";
|
||||
import { registerToolRoutes } from "./routes/tools/index.js";
|
||||
|
||||
// Run before anything else
|
||||
runMigrations();
|
||||
@@ -59,6 +60,9 @@ await authRoutes(app);
|
||||
// File upload/download routes
|
||||
await fileRoutes(app);
|
||||
|
||||
// Tool routes (generic factory-based)
|
||||
await registerToolRoutes(app);
|
||||
|
||||
// Health check
|
||||
app.get("/api/v1/health", async () => ({
|
||||
status: "healthy",
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join, extname, basename } from "node:path";
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { createWorkspace } from "../lib/workspace.js";
|
||||
import { validateImageBuffer } from "../lib/file-validation.js";
|
||||
|
||||
export interface ToolRouteConfig<T> {
|
||||
/** Unique tool identifier, used as the URL path segment. */
|
||||
toolId: string;
|
||||
/** Zod schema that validates the settings JSON from the request. */
|
||||
settingsSchema: z.ZodSchema<T>;
|
||||
/** The processing function: takes input buffer + validated settings, returns output. */
|
||||
process: (
|
||||
inputBuffer: Buffer,
|
||||
settings: T,
|
||||
filename: string,
|
||||
) => Promise<{ buffer: Buffer; filename: string; contentType: string }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a filename to prevent path traversal attacks.
|
||||
*/
|
||||
function sanitizeFilename(raw: string): string {
|
||||
let name = basename(raw);
|
||||
name = name.replace(/\.\./g, "");
|
||||
name = name.replace(/\0/g, "");
|
||||
if (!name || name === "." || name === "..") {
|
||||
name = "image";
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory that registers a POST /api/v1/tools/:toolId route.
|
||||
*
|
||||
* The route accepts multipart with:
|
||||
* - A file part (the image to process)
|
||||
* - A "settings" field containing a JSON string
|
||||
*
|
||||
* The factory handles:
|
||||
* - Multipart parsing
|
||||
* - File validation
|
||||
* - Settings validation via Zod
|
||||
* - Workspace management
|
||||
* - Error handling
|
||||
* - Response formatting
|
||||
*/
|
||||
export function createToolRoute<T>(
|
||||
app: FastifyInstance,
|
||||
config: ToolRouteConfig<T>,
|
||||
): void {
|
||||
app.post(
|
||||
`/api/v1/tools/${config.toolId}`,
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
let fileBuffer: Buffer | null = null;
|
||||
let filename = "image";
|
||||
let settingsRaw: string | null = null;
|
||||
|
||||
// Parse multipart parts
|
||||
try {
|
||||
const parts = request.parts();
|
||||
|
||||
for await (const part of parts) {
|
||||
if (part.type === "file") {
|
||||
// Consume the file stream into a buffer
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of part.file) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
fileBuffer = Buffer.concat(chunks);
|
||||
filename = sanitizeFilename(part.filename ?? "image");
|
||||
} else {
|
||||
// Field part
|
||||
if (part.fieldname === "settings") {
|
||||
settingsRaw = part.value as string;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: "Failed to parse multipart request",
|
||||
details: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
// Require a file
|
||||
if (!fileBuffer || fileBuffer.length === 0) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "No image file provided" });
|
||||
}
|
||||
|
||||
// Validate the uploaded image
|
||||
const validation = await validateImageBuffer(fileBuffer);
|
||||
if (!validation.valid) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: `Invalid image: ${validation.reason}` });
|
||||
}
|
||||
|
||||
// Parse and validate settings
|
||||
let settings: T;
|
||||
try {
|
||||
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
|
||||
const result = config.settingsSchema.safeParse(parsed);
|
||||
if (!result.success) {
|
||||
return reply.status(400).send({
|
||||
error: "Invalid settings",
|
||||
details: result.error.issues.map((i) => ({
|
||||
path: i.path.join("."),
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
}
|
||||
settings = result.data;
|
||||
} catch {
|
||||
return reply.status(400).send({ error: "Settings must be valid JSON" });
|
||||
}
|
||||
|
||||
// Process the image
|
||||
try {
|
||||
const result = await config.process(fileBuffer, settings, filename);
|
||||
|
||||
// Create workspace and save output
|
||||
const jobId = randomUUID();
|
||||
const workspacePath = await createWorkspace(jobId);
|
||||
const outputPath = join(workspacePath, "output", result.filename);
|
||||
await writeFile(outputPath, result.buffer);
|
||||
|
||||
// Also save the original input for reference/download
|
||||
const inputPath = join(workspacePath, "input", filename);
|
||||
await writeFile(inputPath, fileBuffer);
|
||||
|
||||
return reply.send({
|
||||
jobId,
|
||||
downloadUrl: `/api/v1/download/${jobId}/${encodeURIComponent(result.filename)}`,
|
||||
originalSize: fileBuffer.length,
|
||||
processedSize: result.buffer.length,
|
||||
});
|
||||
} catch (err) {
|
||||
// Catch Sharp / processing errors and return a clean API error
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Image processing failed";
|
||||
return reply.status(422).send({
|
||||
error: "Processing failed",
|
||||
details: message,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
|
||||
/**
|
||||
* Registry that imports and registers all tool routes.
|
||||
* Each tool uses the createToolRoute factory from tool-factory.ts.
|
||||
*
|
||||
* Tools will be added here as they are implemented in Phase 2 Tasks 4-10.
|
||||
*/
|
||||
export async function registerToolRoutes(app: FastifyInstance): Promise<void> {
|
||||
// Tool routes will be registered here as they are implemented.
|
||||
// Example:
|
||||
// const { registerResizeTool } = await import("./resize.js");
|
||||
// registerResizeTool(app);
|
||||
app.log.info("Tool routes registered");
|
||||
}
|
||||
Reference in New Issue
Block a user