Serve and create images from within postgresql

This commit is contained in:
thiloho
2024-08-10 17:09:12 +02:00
parent 77338f9cc2
commit 0866e2631d
9 changed files with 158 additions and 171 deletions

View File

@@ -1,66 +0,0 @@
import { randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { extname, join, relative } from "node:path";
import { ALLOWED_MIME_TYPES } from "../utils";
export const handleFileUpload = async (
file: File,
websiteId: string,
userId: string,
session_token: string | undefined,
customFetch: typeof fetch
) => {
if (file.size === 0) return undefined;
const MAX_FILE_SIZE = 1024 * 1024;
if (file.size > MAX_FILE_SIZE) {
return {
success: false,
message: `File size exceeds the maximum limit of ${MAX_FILE_SIZE / 1024 / 1024} MB.`
};
}
if (!ALLOWED_MIME_TYPES.includes(file.type)) {
return {
success: false,
message: "Invalid file type. JPEG, PNG, SVG and WEBP are allowed."
};
}
const buffer = Buffer.from(await file.arrayBuffer());
const uploadDir = join(process.cwd(), "static", "user-uploads", userId);
await mkdir(uploadDir, { recursive: true });
const fileId = randomUUID();
const fileExtension = extname(file.name);
const filepath = join(uploadDir, `${fileId}${fileExtension}`);
await writeFile(filepath, buffer);
const relativePath = relative(join(process.cwd(), "static"), filepath);
const res = await customFetch("http://localhost:3000/media", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session_token}`,
Prefer: "return=representation",
Accept: "application/vnd.pgrst.object+json"
},
body: JSON.stringify({
website_id: websiteId,
user_id: userId,
original_name: file.name,
file_system_path: relativePath
})
});
const response = await res.json();
if (!res.ok) {
return { success: false, message: response.message };
}
return { success: true, content: response.id };
};

View File

@@ -1,9 +1,8 @@
import { handleFileUpload } from "$lib/server/utils.js";
import type { Actions, PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ params, fetch, cookies, url }) => {
const globalSettingsData = await fetch(
`http://localhost:3000/settings?website_id=eq.${params.websiteId}&select=*,media(*)`,
`http://localhost:3000/settings?website_id=eq.${params.websiteId}`,
{
method: "GET",
headers: {
@@ -14,17 +13,14 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url }) => {
}
);
const headerData = await fetch(
`http://localhost:3000/header?website_id=eq.${params.websiteId}&select=*,media(*)`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json"
}
const headerData = await fetch(`http://localhost:3000/header?website_id=eq.${params.websiteId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json"
}
);
});
const footerData = await fetch(`http://localhost:3000/footer?website_id=eq.${params.websiteId}`, {
method: "GET",
@@ -49,18 +45,25 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url }) => {
export const actions: Actions = {
updateGlobal: async ({ request, fetch, cookies, params, locals }) => {
const data = await request.formData();
const faviconFile = data.get("favicon") as File;
const favicon = await handleFileUpload(
faviconFile,
params.websiteId,
locals.user.id,
cookies.get("session_token"),
fetch
);
if (favicon?.success === false) {
return favicon;
const uploadedImageData = await fetch(`http://localhost:3000/rpc/upload_file`, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json",
"X-Website-Id": params.websiteId,
"X-Mimetype": faviconFile.type,
"X-Original-Filename": faviconFile.name
},
body: await faviconFile.arrayBuffer()
});
const uploadedImage = await uploadedImageData.json();
if (!uploadedImageData.ok) {
return { success: false, message: uploadedImage.message };
}
const res = await fetch(`http://localhost:3000/settings?website_id=eq.${params.websiteId}`, {
@@ -72,7 +75,7 @@ export const actions: Actions = {
body: JSON.stringify({
accent_color_light_theme: data.get("accent-color-light"),
accent_color_dark_theme: data.get("accent-color-dark"),
favicon_image: favicon?.content
favicon_image: uploadedImage.file_id
})
});
@@ -86,20 +89,27 @@ export const actions: Actions = {
message: "Successfully updated global settings"
};
},
updateHeader: async ({ request, fetch, cookies, locals, params }) => {
updateHeader: async ({ request, fetch, cookies, params }) => {
const data = await request.formData();
const logoImage = data.get("logo-image") as File;
const logoFile = data.get("logo-image") as File;
const logo = await handleFileUpload(
logoFile,
params.websiteId,
locals.user.id,
cookies.get("session_token"),
fetch
);
const uploadedImageData = await fetch(`http://localhost:3000/rpc/upload_file`, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json",
"X-Website-Id": params.websiteId,
"X-Mimetype": logoImage.type,
"X-Original-Filename": logoImage.name
},
body: await logoImage.arrayBuffer()
});
if (logo?.success === false) {
return logo;
const uploadedImage = await uploadedImageData.json();
if (!uploadedImageData.ok) {
return { success: false, message: uploadedImage.message };
}
const res = await fetch(`http://localhost:3000/header?website_id=eq.${params.websiteId}`, {
@@ -111,7 +121,7 @@ export const actions: Actions = {
body: JSON.stringify({
logo_type: data.get("logo-type"),
logo_text: data.get("logo-text"),
logo_image: logo?.content
logo_image: uploadedImage.file_id
})
});

View File

@@ -53,11 +53,11 @@
Favicon:
<input type="file" name="favicon" accept={ALLOWED_MIME_TYPES.join(", ")} />
</label>
{#if data.globalSettings.media}
{#if data.globalSettings.favicon_image}
<Modal id="preview-favicon-global-{data.globalSettings.website_id}" text="Preview">
<img
src={`http://localhost:5173/${data.globalSettings.media.file_system_path}`}
alt={data.globalSettings.media.original_name}
src={`http://localhost:3000/rpc/retrieve_file?id=${data.globalSettings.favicon_image}`}
alt=""
/>
</Modal>
{/if}
@@ -107,11 +107,11 @@
required={data.header.logo_type === "image"}
/>
</label>
{#if data.header.media}
{#if data.header.logo_image}
<Modal id="preview-logo-header-{data.header.website_id}" text="Preview">
<img
src={`http://localhost:5173/${data.header.media.file_system_path}`}
alt={data.header.media.original_name}
src={`http://localhost:3000/rpc/retrieve_file?id=${data.header.logo_image}`}
alt=""
/>
</Modal>
{/if}

View File

@@ -1,18 +1,14 @@
import { handleFileUpload } from "$lib/server/utils.js";
import type { Actions, PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ parent, params, cookies, fetch }) => {
const articleData = await fetch(
`http://localhost:3000/article?id=eq.${params.articleId}&select=*,media(*)`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json"
}
const articleData = await fetch(`http://localhost:3000/article?id=eq.${params.articleId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json"
}
);
});
const article = await articleData.json();
const { website } = await parent();
@@ -23,18 +19,25 @@ export const load: PageServerLoad = async ({ parent, params, cookies, fetch }) =
export const actions: Actions = {
default: async ({ fetch, cookies, request, params, locals }) => {
const data = await request.formData();
const coverFile = data.get("cover-image") as File;
const cover = await handleFileUpload(
coverFile,
params.websiteId,
locals.user.id,
cookies.get("session_token"),
fetch
);
if (cover?.success === false) {
return cover;
const uploadedImageData = await fetch(`http://localhost:3000/rpc/upload_file`, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
Authorization: `Bearer ${cookies.get("session_token")}`,
Accept: "application/vnd.pgrst.object+json",
"X-Website-Id": params.websiteId,
"X-Mimetype": coverFile.type,
"X-Original-Filename": coverFile.name
},
body: await coverFile.arrayBuffer()
});
const uploadedImage = await uploadedImageData.json();
if (!uploadedImageData.ok) {
return { success: false, message: uploadedImage.message };
}
const res = await fetch(`http://localhost:3000/article?id=eq.${params.articleId}`, {
@@ -47,7 +50,7 @@ export const actions: Actions = {
title: data.get("title"),
meta_description: data.get("description"),
meta_author: data.get("author"),
cover_image: cover?.content,
cover_image: uploadedImage.file_id,
publication_date: data.get("publication-date"),
main_content: data.get("main-content")
})

View File

@@ -66,11 +66,11 @@
Cover image:
<input type="file" name="cover-image" accept={ALLOWED_MIME_TYPES.join(", ")} />
</label>
{#if data.article.media}
{#if data.article.cover_image}
<Modal id="preview-cover-article-{data.article.id}" text="Preview">
<img
src={`http://localhost:5173/${data.article.media.file_system_path}`}
alt={data.article.media.original_name}
src={`http://localhost:3000/rpc/retrieve_file?id=${data.article.cover_image}`}
alt=""
/>
</Modal>
{/if}