Revert "images fixing with database saves"
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
This reverts commit c45e054787.
This commit is contained in:
@ -1,12 +1,17 @@
|
||||
import { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { db } from '../config/database.js';
|
||||
import { galleryImages } from '../db/schema.js';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Fastify JSON schema for gallery image body
|
||||
const galleryBodyJsonSchema = {
|
||||
type: 'object',
|
||||
required: ['altText', 'displayOrder'],
|
||||
required: ['imageUrl', 'altText', 'displayOrder'],
|
||||
properties: {
|
||||
imageUrl: { type: 'string', minLength: 1 },
|
||||
altText: { type: 'string', minLength: 1, maxLength: 200 },
|
||||
displayOrder: { type: 'integer', minimum: 0 },
|
||||
isPublished: { type: 'boolean' },
|
||||
@ -17,99 +22,46 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
|
||||
// PUBLIC: List published gallery images (no auth required)
|
||||
fastify.get('/gallery/public', async () => {
|
||||
const images = await db.select({
|
||||
id: galleryImages.id,
|
||||
altText: galleryImages.altText,
|
||||
displayOrder: galleryImages.displayOrder,
|
||||
isPublished: galleryImages.isPublished,
|
||||
}).from(galleryImages)
|
||||
.where(eq(galleryImages.isPublished, true))
|
||||
.orderBy(galleryImages.displayOrder);
|
||||
|
||||
// Return with generated URLs pointing to the image endpoint
|
||||
return {
|
||||
images: images.map(img => ({
|
||||
...img,
|
||||
imageUrl: `/api/gallery/${img.id}/image`,
|
||||
}))
|
||||
};
|
||||
});
|
||||
|
||||
// Serve image data
|
||||
fastify.get('/gallery/:id/image', async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const [image] = await db.select({
|
||||
imageData: galleryImages.imageData,
|
||||
mimeType: galleryImages.mimeType,
|
||||
}).from(galleryImages).where(eq(galleryImages.id, id)).limit(1);
|
||||
|
||||
if (!image || !image.imageData) {
|
||||
return reply.code(404).send({ error: 'Image not found' });
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(image.imageData, 'base64');
|
||||
return reply
|
||||
.header('Content-Type', image.mimeType || 'image/webp')
|
||||
.header('Cache-Control', 'public, max-age=31536000')
|
||||
.send(buffer);
|
||||
const images = await db.select().from(galleryImages)
|
||||
.where(eq(galleryImages.isPublished, true))
|
||||
.orderBy(galleryImages.displayOrder);
|
||||
return { images };
|
||||
});
|
||||
|
||||
// List all gallery images - admin only
|
||||
fastify.get('/gallery', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async () => {
|
||||
const images = await db.select({
|
||||
id: galleryImages.id,
|
||||
altText: galleryImages.altText,
|
||||
displayOrder: galleryImages.displayOrder,
|
||||
isPublished: galleryImages.isPublished,
|
||||
}).from(galleryImages).orderBy(galleryImages.displayOrder);
|
||||
|
||||
return {
|
||||
images: images.map(img => ({
|
||||
...img,
|
||||
imageUrl: `/api/gallery/${img.id}/image`,
|
||||
}))
|
||||
};
|
||||
}, async (request, reply) => {
|
||||
const images = await db.select().from(galleryImages).orderBy(galleryImages.displayOrder);
|
||||
return { images };
|
||||
});
|
||||
|
||||
// Get single gallery image metadata
|
||||
// Get single gallery image
|
||||
fastify.get('/gallery/:id', {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const [image] = await db.select({
|
||||
id: galleryImages.id,
|
||||
altText: galleryImages.altText,
|
||||
displayOrder: galleryImages.displayOrder,
|
||||
isPublished: galleryImages.isPublished,
|
||||
}).from(galleryImages).where(eq(galleryImages.id, id)).limit(1);
|
||||
const image = await db.select().from(galleryImages).where(eq(galleryImages.id, id)).limit(1);
|
||||
|
||||
if (!image) {
|
||||
if (image.length === 0) {
|
||||
return reply.code(404).send({ error: 'Image not found' });
|
||||
}
|
||||
|
||||
return {
|
||||
image: {
|
||||
...image,
|
||||
imageUrl: `/api/gallery/${image.id}/image`,
|
||||
}
|
||||
};
|
||||
return { image: image[0] };
|
||||
});
|
||||
|
||||
// Create gallery image (JSON, no file)
|
||||
// Create gallery image
|
||||
fastify.post('/gallery', {
|
||||
schema: { body: galleryBodyJsonSchema },
|
||||
schema: {
|
||||
body: galleryBodyJsonSchema,
|
||||
},
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const data = request.body as any;
|
||||
|
||||
const [newImage] = await db.insert(galleryImages).values(data).returning();
|
||||
return reply.code(201).send({
|
||||
image: {
|
||||
...newImage,
|
||||
imageUrl: `/api/gallery/${newImage.id}/image`,
|
||||
}
|
||||
});
|
||||
|
||||
return reply.code(201).send({ image: newImage });
|
||||
});
|
||||
|
||||
// Upload image file (multipart)
|
||||
@ -117,6 +69,7 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
try {
|
||||
// Expect a single file field named "file"
|
||||
const file = await (request as any).file();
|
||||
if (!file) {
|
||||
return reply.code(400).send({ error: 'No file uploaded' });
|
||||
@ -131,6 +84,11 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
return reply.code(400).send({ error: 'Only image uploads are allowed' });
|
||||
}
|
||||
|
||||
// Prepare directories - use persistent volume for Fly.io
|
||||
const dataDir = process.env.GIT_WORKSPACE_DIR || path.join(process.cwd(), 'data');
|
||||
const uploadDir = path.join(dataDir, 'public', 'images', 'gallery');
|
||||
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
|
||||
|
||||
// Read uploaded stream into buffer
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of file.file) {
|
||||
@ -138,44 +96,46 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
}
|
||||
const inputBuffer = Buffer.concat(chunks);
|
||||
|
||||
// Process image and convert to base64
|
||||
let imageData: string;
|
||||
let mimeType = 'image/webp';
|
||||
// Generate filename
|
||||
const stamp = Date.now().toString(36);
|
||||
const rand = Math.random().toString(36).slice(2, 8);
|
||||
const baseName = `${stamp}-${rand}`;
|
||||
|
||||
// Try to convert to webp and limit size; fallback to original
|
||||
let outBuffer: Buffer | null = null;
|
||||
let outExt = '.webp';
|
||||
try {
|
||||
// Lazy load sharp only when needed
|
||||
const sharp = (await import('sharp')).default;
|
||||
const processedBuffer = await sharp(inputBuffer)
|
||||
.rotate()
|
||||
.resize({ width: 1600, withoutEnlargement: true })
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer();
|
||||
imageData = processedBuffer.toString('base64');
|
||||
outBuffer = await sharp(inputBuffer)
|
||||
.rotate()
|
||||
.resize({ width: 1600, withoutEnlargement: true })
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer();
|
||||
} catch (err) {
|
||||
fastify.log.warn({ err }, 'Sharp processing failed, using original image');
|
||||
imageData = inputBuffer.toString('base64');
|
||||
mimeType = mime;
|
||||
outBuffer = inputBuffer;
|
||||
// naive extension from mimetype
|
||||
const extFromMime = mime.split('/')[1] || 'bin';
|
||||
outExt = '.' + extFromMime.replace(/[^a-z0-9]/gi, '').toLowerCase();
|
||||
}
|
||||
|
||||
// Store in DB
|
||||
const filename = baseName + outExt;
|
||||
const destPath = path.join(uploadDir, filename);
|
||||
fs.writeFileSync(destPath, outBuffer);
|
||||
|
||||
// Public URL (served via /static)
|
||||
const publicUrl = `/images/gallery/${filename}`;
|
||||
|
||||
// Store in DB (optional but useful)
|
||||
const [row] = await db.insert(galleryImages).values({
|
||||
imageData,
|
||||
mimeType,
|
||||
altText: altText || 'Gallery image',
|
||||
imageUrl: publicUrl,
|
||||
altText: altText || filename,
|
||||
displayOrder,
|
||||
isPublished: true,
|
||||
}).returning({
|
||||
id: galleryImages.id,
|
||||
altText: galleryImages.altText,
|
||||
displayOrder: galleryImages.displayOrder,
|
||||
isPublished: galleryImages.isPublished,
|
||||
});
|
||||
}).returning();
|
||||
|
||||
return reply.code(201).send({
|
||||
image: {
|
||||
...row,
|
||||
imageUrl: `/api/gallery/${row.id}/image`,
|
||||
}
|
||||
});
|
||||
return reply.code(201).send({ image: row });
|
||||
|
||||
} catch (err) {
|
||||
fastify.log.error({ err }, 'Upload failed');
|
||||
@ -185,33 +145,25 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
|
||||
// Update gallery image
|
||||
fastify.put('/gallery/:id', {
|
||||
schema: { body: galleryBodyJsonSchema },
|
||||
schema: {
|
||||
body: galleryBodyJsonSchema,
|
||||
},
|
||||
preHandler: [fastify.authenticate],
|
||||
}, async (request, reply) => {
|
||||
const { id } = request.params as { id: string };
|
||||
const data = request.body as any;
|
||||
|
||||
const [updated] = await db
|
||||
.update(galleryImages)
|
||||
.set(data)
|
||||
.where(eq(galleryImages.id, id))
|
||||
.returning({
|
||||
id: galleryImages.id,
|
||||
altText: galleryImages.altText,
|
||||
displayOrder: galleryImages.displayOrder,
|
||||
isPublished: galleryImages.isPublished,
|
||||
});
|
||||
.update(galleryImages)
|
||||
.set(data)
|
||||
.where(eq(galleryImages.id, id))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return reply.code(404).send({ error: 'Image not found' });
|
||||
}
|
||||
|
||||
return {
|
||||
image: {
|
||||
...updated,
|
||||
imageUrl: `/api/gallery/${updated.id}/image`,
|
||||
}
|
||||
};
|
||||
return { image: updated };
|
||||
});
|
||||
|
||||
// Delete gallery image
|
||||
@ -221,9 +173,9 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
const { id } = request.params as { id: string };
|
||||
|
||||
const [deleted] = await db
|
||||
.delete(galleryImages)
|
||||
.where(eq(galleryImages.id, id))
|
||||
.returning();
|
||||
.delete(galleryImages)
|
||||
.where(eq(galleryImages.id, id))
|
||||
.returning();
|
||||
|
||||
if (!deleted) {
|
||||
return reply.code(404).send({ error: 'Image not found' });
|
||||
@ -257,6 +209,7 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
}, async (request, reply) => {
|
||||
const { orders } = request.body as { orders: Array<{ id: string; displayOrder: number }> };
|
||||
|
||||
// Update all in synchronous transaction (better-sqlite3 requirement)
|
||||
db.transaction((tx: any) => {
|
||||
for (const { id, displayOrder } of orders) {
|
||||
tx.update(galleryImages).set({ displayOrder }).where(eq(galleryImages.id, id)).run?.();
|
||||
@ -267,4 +220,4 @@ const galleryRoute: FastifyPluginAsync = async (fastify) => {
|
||||
});
|
||||
};
|
||||
|
||||
export default galleryRoute;
|
||||
export default galleryRoute;
|
||||
|
||||
Reference in New Issue
Block a user