feat(image-service): standalone processor
This commit is contained in:
80
apps/image-service/src/index.ts
Normal file
80
apps/image-service/src/index.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import Fastify from "fastify";
|
||||
import { processImageWithSmartCrop } from "@mintel/image-processor";
|
||||
|
||||
const fastify = Fastify({
|
||||
logger: true,
|
||||
});
|
||||
|
||||
fastify.get("/unsafe/:options/:urlSafeB64", async (request, reply) => {
|
||||
// Compatibility endpoint for old imgproxy calls (optional, but requested by some systems sometimes)
|
||||
// For now, replacing logic in clients is preferred. So we just redirect or error.
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Legacy imgproxy API not supported. Use /process" });
|
||||
});
|
||||
|
||||
fastify.get("/process", async (request, reply) => {
|
||||
const query = request.query as {
|
||||
url?: string;
|
||||
w?: string;
|
||||
h?: string;
|
||||
q?: string;
|
||||
format?: string;
|
||||
};
|
||||
|
||||
const { url } = query;
|
||||
const width = parseInt(query.w || "800", 10);
|
||||
const height = parseInt(query.h || "600", 10);
|
||||
const quality = parseInt(query.q || "80", 10);
|
||||
const format = (query.format || "webp") as "webp" | "jpeg" | "png" | "avif";
|
||||
|
||||
if (!url) {
|
||||
return reply.status(400).send({ error: 'Parameter "url" is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
return reply
|
||||
.status(response.status)
|
||||
.send({
|
||||
error: `Failed to fetch source image: ${response.statusText}`,
|
||||
});
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
const processedBuffer = await processImageWithSmartCrop(buffer, {
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
quality,
|
||||
});
|
||||
|
||||
reply.header("Content-Type", `image/${format}`);
|
||||
reply.header("Cache-Control", "public, max-age=31536000, immutable");
|
||||
return reply.send(processedBuffer);
|
||||
} catch (err) {
|
||||
fastify.log.error(err);
|
||||
return reply
|
||||
.status(500)
|
||||
.send({ error: "Internal Server Error processing image" });
|
||||
}
|
||||
});
|
||||
|
||||
fastify.get("/health", async () => {
|
||||
return { status: "ok" };
|
||||
});
|
||||
|
||||
const start = async () => {
|
||||
try {
|
||||
await fastify.listen({ port: 8080, host: "0.0.0.0" });
|
||||
console.log(`Server listening on 8080`);
|
||||
} catch (err) {
|
||||
fastify.log.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
start();
|
||||
Reference in New Issue
Block a user