feat: add POST /api/jobs and GET /api/formats endpoints
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
+116
@@ -0,0 +1,116 @@
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import multer from 'multer';
|
||||
import { rateLimit } from 'express-rate-limit';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { resolve as resolveConverter, listTargetFormats } from './converters/registry.js';
|
||||
import { registerImageConverters } from './converters/image.js';
|
||||
import { registerImageToPdfConverter } from './converters/imageToPdf.js';
|
||||
import { registerDocumentConverters } from './converters/document.js';
|
||||
import { resolveInputFormat } from './mime.js';
|
||||
import { deleteIfExists } from './storage.js';
|
||||
import { createJob, getJobById } from './jobs/jobRepository.js';
|
||||
|
||||
let convertersRegistered = false;
|
||||
|
||||
function registerAllConverters() {
|
||||
if (convertersRegistered) return;
|
||||
registerImageConverters();
|
||||
registerImageToPdfConverter();
|
||||
registerDocumentConverters();
|
||||
convertersRegistered = true;
|
||||
}
|
||||
|
||||
export function createApp(config, pool) {
|
||||
registerAllConverters();
|
||||
|
||||
const app = express();
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => cb(null, path.join(config.storageDir, 'uploads')),
|
||||
filename: (req, file, cb) => {
|
||||
const ext = path.extname(file.originalname).slice(1).toLowerCase();
|
||||
cb(null, `${uuidv4()}.${ext}`);
|
||||
},
|
||||
});
|
||||
|
||||
const upload = multer({
|
||||
storage,
|
||||
limits: {
|
||||
fileSize: config.maxFileSizeMb * 1024 * 1024,
|
||||
files: 10,
|
||||
},
|
||||
});
|
||||
|
||||
const jobsRateLimiter = rateLimit({
|
||||
windowMs: config.rateLimitWindowMinutes * 60 * 1000,
|
||||
limit: config.rateLimitMaxJobs,
|
||||
standardHeaders: 'draft-8',
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
app.get('/api/formats', (req, res) => {
|
||||
const source = String(req.query.source ?? '').toLowerCase();
|
||||
res.json({ targets: listTargetFormats(source) });
|
||||
});
|
||||
|
||||
app.post('/api/jobs', jobsRateLimiter, upload.array('files', 10), async (req, res) => {
|
||||
if (!req.files || req.files.length === 0) {
|
||||
return res.status(400).json({ error: 'No files uploaded' });
|
||||
}
|
||||
|
||||
let targetFormats;
|
||||
try {
|
||||
targetFormats = JSON.parse(req.body.targetFormats ?? '[]');
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'targetFormats must be a JSON array' });
|
||||
}
|
||||
|
||||
if (!Array.isArray(targetFormats) || targetFormats.length !== req.files.length) {
|
||||
return res.status(400).json({ error: 'targetFormats must have one entry per uploaded file' });
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (let i = 0; i < req.files.length; i += 1) {
|
||||
const file = req.files[i];
|
||||
const targetFormat = targetFormats[i];
|
||||
const id = path.basename(file.filename, path.extname(file.filename));
|
||||
const sourceFormat = path.extname(file.filename).slice(1).toLowerCase();
|
||||
|
||||
const { mime, valid } = await resolveInputFormat(file.path, sourceFormat);
|
||||
if (!valid) {
|
||||
await deleteIfExists(file.path);
|
||||
results.push({ file: file.originalname, error: 'File content does not match its extension' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const registryEntry = resolveConverter(sourceFormat, targetFormat);
|
||||
if (!registryEntry) {
|
||||
await deleteIfExists(file.path);
|
||||
results.push({
|
||||
file: file.originalname,
|
||||
error: `Unsupported conversion: ${sourceFormat} to ${targetFormat}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const expiresAt = new Date(Date.now() + config.retentionHours * 3600 * 1000);
|
||||
await createJob(pool, {
|
||||
id,
|
||||
family: registryEntry.family,
|
||||
sourceFormat,
|
||||
targetFormat,
|
||||
originalFilename: file.originalname,
|
||||
inputPath: file.filename,
|
||||
inputMimeType: mime,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
results.push({ file: file.originalname, id, status: 'pending' });
|
||||
}
|
||||
|
||||
res.status(201).json({ jobs: results });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { createApp } from '../../src/app.js';
|
||||
import { getPool, closePool } from '../../src/db.js';
|
||||
import { loadConfig } from '../../src/config.js';
|
||||
import { getJobById } from '../../src/jobs/jobRepository.js';
|
||||
import { ensureStorageDirs } from '../../src/storage.js';
|
||||
|
||||
let app;
|
||||
let pool;
|
||||
let config;
|
||||
|
||||
beforeAll(async () => {
|
||||
config = { ...loadConfig(), storageDir: await fs.mkdtemp(path.join(os.tmpdir(), 'converter-api-')) };
|
||||
await ensureStorageDirs(config);
|
||||
pool = getPool(config);
|
||||
app = createApp(config, pool);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await closePool();
|
||||
await fs.rm(config.storageDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await pool.query('DELETE FROM conversion_jobs');
|
||||
});
|
||||
|
||||
describe('GET /api/formats', () => {
|
||||
it('lists valid target formats for a known source format', async () => {
|
||||
const response = await request(app).get('/api/formats').query({ source: 'png' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.targets).toContain('webp');
|
||||
expect(response.body.targets).toContain('pdf');
|
||||
});
|
||||
|
||||
it('returns an empty list for an unknown source format', async () => {
|
||||
const response = await request(app).get('/api/formats').query({ source: 'made-up' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.targets).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/jobs', () => {
|
||||
it('creates a pending job for a valid image upload', async () => {
|
||||
const fixturePath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png');
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/jobs')
|
||||
.field('targetFormats', JSON.stringify(['webp']))
|
||||
.attach('files', fixturePath, 'photo.png');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.jobs).toHaveLength(1);
|
||||
expect(response.body.jobs[0].status).toBe('pending');
|
||||
expect(response.body.jobs[0].file).toBe('photo.png');
|
||||
|
||||
const job = await getJobById(pool, response.body.jobs[0].id);
|
||||
expect(job.status).toBe('pending');
|
||||
expect(job.sourceFormat).toBe('png');
|
||||
expect(job.targetFormat).toBe('webp');
|
||||
expect(job.originalFilename).toBe('photo.png');
|
||||
expect(job.inputMimeType).toBe('image/png');
|
||||
});
|
||||
|
||||
it('rejects a file whose content does not match its extension, without failing the whole batch', async () => {
|
||||
const fakePath = path.join(config.storageDir, 'fake.png');
|
||||
await fs.writeFile(fakePath, 'not actually a png');
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/jobs')
|
||||
.field('targetFormats', JSON.stringify(['webp']))
|
||||
.attach('files', fakePath, 'fake.png');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.jobs[0].error).toMatch(/does not match/);
|
||||
|
||||
await fs.unlink(fakePath);
|
||||
});
|
||||
|
||||
it('rejects an unsupported source/target pair', async () => {
|
||||
const fixturePath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png');
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/jobs')
|
||||
.field('targetFormats', JSON.stringify(['made-up-format']))
|
||||
.attach('files', fixturePath, 'photo.png');
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(response.body.jobs[0].error).toMatch(/Unsupported conversion/);
|
||||
});
|
||||
|
||||
it('returns 400 when targetFormats length does not match the number of files', async () => {
|
||||
const fixturePath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png');
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/jobs')
|
||||
.field('targetFormats', JSON.stringify([]))
|
||||
.attach('files', fixturePath, 'photo.png');
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
|
||||
it('returns 400 when no files are uploaded', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/jobs')
|
||||
.field('targetFormats', JSON.stringify([]));
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user