1 import Fastify from 'fastify'; 2 import { exec } from 'node:child_process'; 3 import { promisify } from 'node:util'; 4 import { randomUUID } from 'node:crypto'; 5 import fs from 'node:fs/promises'; 6 import os from 'node:os'; 7 import path from 'node:path'; 8 9 const run = promisify(exec); 10 const app = Fastify({ logger: true }); 11 12 interface ThumbnailBody { 13 imageUrl: string; 14 width: string; 15 } 16 17 app.post<{ Body: ThumbnailBody }>('/api/thumbnails', async (request, reply) => { 18 const { imageUrl, width } = request.body; 19 20 const response = await fetch(imageUrl); 21 22 if (!response.ok) { 23 return reply.code(422).send({ error: 'Could not download the image' }); 24 } 25 26 const id = randomUUID(); 27 const input = path.join(os.tmpdir(), `${id}-source`); 28 const output = path.join(os.tmpdir(), `${id}.webp`); 29 30 await fs.writeFile(input, Buffer.from(await response.arrayBuffer())); 31 await run(`magick ${input} -resize ${width}x ${output}`); 32 33 const thumbnail = await fs.readFile(output); 34 await fs.rm(input); 35 await fs.rm(output); 36 37 return reply.type('image/webp').send(thumbnail); 38 }); 39 40 await app.listen({ port: 3000, host: '0.0.0.0' });