u
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
import express from 'express';
|
||||
import * as db from '../../db/brand.js';
|
||||
|
||||
const AVIF_BODY_LIMIT = 10 * 1024 * 1024;
|
||||
|
||||
function requireSelectedCompany(req) {
|
||||
const companyId = req.user.selectedCompanyId;
|
||||
if (companyId == null) {
|
||||
@@ -15,6 +18,7 @@ function brandErrorStatus(error) {
|
||||
if (error.message === 'Brand not found') return 404;
|
||||
if (error.message === 'Invalid brand') return 400;
|
||||
if (error.message === 'Brand in use') return 409;
|
||||
if (error.message === 'Image not found') return 404;
|
||||
return 500;
|
||||
}
|
||||
|
||||
@@ -237,4 +241,55 @@ export function register(app, basePath = '') {
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post(
|
||||
`${basePath}/brand/:id/image`,
|
||||
express.raw({ type: ['image/avif', 'application/octet-stream'], limit: AVIF_BODY_LIMIT }),
|
||||
async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
const imageBuffer = Buffer.isBuffer(req.body) ? req.body : null;
|
||||
if (!imageBuffer?.length) {
|
||||
return res.status(400).json({ error: 'AVIF image body is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const brand = await db.addImage(req.user.id, id, imageBuffer);
|
||||
res.status(201).json({ brand });
|
||||
} catch (error) {
|
||||
const status = brandErrorStatus(error);
|
||||
if (status === 500) console.error('Add brand image failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.delete(`${basePath}/brand/:id/image`, async (req, res) => {
|
||||
const selected = requireSelectedCompany(req);
|
||||
if (selected.error) {
|
||||
return res.status(400).json({ error: selected.error });
|
||||
}
|
||||
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
return res.status(400).json({ error: 'id is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
const brand = await db.deleteImage(req.user.id, id);
|
||||
res.status(200).json({ brand });
|
||||
} catch (error) {
|
||||
const status = brandErrorStatus(error);
|
||||
if (status === 500) console.error('Delete brand image failed:', error);
|
||||
res.status(status).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user