Skip to content

Commit 7136302

Browse files
committed
chore: Refactor getBackgroundImages to improve image URL generation
1 parent 8eb9f11 commit 7136302

File tree

5 files changed

+50
-2
lines changed

5 files changed

+50
-2
lines changed

src/lib/db/getBackgroundImages.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import { ensureBucketExists, getObjectUrl, s3Client } from "$lib/server/s3";
22
import { ListObjectsV2Command } from "@aws-sdk/client-s3";
33

4+
/**
5+
* Retrieves a random background image URL from the "backgrounds" bucket.
6+
* If the randomly selected image is ".emptyFolderPlaceholder", it recursively calls itself to get another image.
7+
* If no images are found in the bucket, a default image URL is returned.
8+
*
9+
* @returns A Promise that resolves to a string representing the URL of the background image.
10+
*/
411
export const getBackgroundImages = async (): Promise<string> => {
512
await ensureBucketExists("backgrounds");
613

src/lib/server/s3.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ import {
1010
import { env } from "$env/dynamic/private";
1111
console.log(env.AWS_ACCESS_KEY_ID as string);
1212

13+
/**
14+
* Configuration object for S3 client.
15+
*/
1316
const s3Config: S3ClientConfig = {
1417
region: (env.AWS_REGION as string) || "us-east-1",
1518
credentials: {
@@ -22,6 +25,12 @@ const s3Config: S3ClientConfig = {
2225

2326
export const s3Client = new S3Client(s3Config);
2427

28+
/**
29+
* Ensures that a bucket exists in Amazon S3. If the bucket does not exist, it creates the bucket and sets a bucket policy to allow public read access.
30+
* If the bucket already exists, it logs a message indicating that the bucket already exists.
31+
* @param bucketName - The name of the bucket to ensure exists.
32+
* @throws Throws an error if there is an issue with creating the bucket or setting the bucket policy.
33+
*/
2534
export const ensureBucketExists = async (bucketName: string): Promise<void> => {
2635
const headBucketCommand = new HeadBucketCommand({ Bucket: bucketName });
2736

@@ -71,6 +80,14 @@ export const ensureBucketExists = async (bucketName: string): Promise<void> => {
7180
}
7281
};
7382

83+
/**
84+
* Uploads an object to an S3 bucket.
85+
* @param bucketName - The name of the S3 bucket.
86+
* @param fileName - The name of the file to be uploaded.
87+
* @param fileBuffer - The file content as a Buffer.
88+
* @returns A Promise that resolves to the URL of the uploaded object.
89+
* @throws If there is an error during the upload process.
90+
*/
7491
export const uploadObject = async (
7592
bucketName: string,
7693
fileName: string,
@@ -97,6 +114,12 @@ export const uploadObject = async (
97114
}
98115
};
99116

117+
/**
118+
* Deletes an object from an S3 bucket.
119+
* @param bucketName - The name of the S3 bucket.
120+
* @param fileName - The name of the file to delete.
121+
* @throws Throws an error if there is an issue deleting the object.
122+
*/
100123
export const deleteObject = async (bucketName: string, fileName: string) => {
101124
const deleteObjectCommand = new DeleteObjectCommand({
102125
Bucket: bucketName,
@@ -114,6 +137,12 @@ export const deleteObject = async (bucketName: string, fileName: string) => {
114137
}
115138
};
116139

140+
/**
141+
* Returns the URL of an object in the specified bucket.
142+
* @param bucketName - The name of the bucket.
143+
* @param fileName - The name of the file.
144+
* @returns The URL of the object.
145+
*/
117146
export const getObjectUrl = (bucketName: string, fileName: string): string => {
118147
let objectUrl: string;
119148
let endpoint: string = "";
@@ -123,6 +152,9 @@ export const getObjectUrl = (bucketName: string, fileName: string): string => {
123152
endpoint = env.AWS_S3_ENDPOINT as string;
124153
}
125154

155+
// This code is not as clean as it could be, but it works for whats needed. Help is welcome to clean it up!
156+
// Currently supports Amazon S3, Google Cloud Storage, DigitalOcean Spaces, and Supabase Storage as well as self-hosted MinIO.
157+
126158
if (endpoint.includes("amazonaws.com")) {
127159
// Amazon S3
128160
objectUrl = `https://${bucketName}.s3.${env.AWS_REGION}.amazonaws.com/${fileName}`;

src/routes/api/upload/+server.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ import { deleteObject, ensureBucketExists, uploadObject } from "$lib/server/s3";
66
import type { RequestEvent } from "@sveltejs/kit";
77
import { generateId } from "lucia";
88

9+
/**
10+
* Handles the POST request for uploading a file to S3 storage.
11+
*
12+
* @param event - The request event object.
13+
* @returns A promise that resolves to a response object.
14+
*/
915
export async function POST(event: RequestEvent): Promise<Response> {
1016
try {
1117
const contentType = event.request.headers.get("content-type") ?? "";

src/routes/signup/+page.server.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ import type { DatabaseUser } from "$lib/server/auth";
99
import type { Actions, PageServerLoad } from "./$types";
1010
import { userTable } from "$lib/db/schema";
1111
import { eq } from "drizzle-orm";
12+
import { getBackgroundImages } from "$lib/db/getBackgroundImages";
1213

1314
export const load: PageServerLoad = async (event) => {
1415
if (event.locals.user) {
1516
return redirect(302, "/");
1617
}
17-
return {};
18+
return { image: await getBackgroundImages() };
1819
};
1920

2021
export const actions: Actions = {

src/routes/signup/+page.svelte

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import type { SubmitFunction } from "@sveltejs/kit";
77
import { onMount } from "svelte";
88
9+
export let data;
10+
911
let errors: { message?: string } = {};
1012
let backgroundImageUrl = "https://source.unsplash.com/random/?mountains";
1113
@@ -37,7 +39,7 @@
3739

3840
<div
3941
class="min-h-screen bg-no-repeat bg-cover flex items-center justify-center"
40-
style="background-image: url('{backgroundImageUrl}')"
42+
style="background-image: url('{data.image}')"
4143
>
4244
<div class="card card-compact w-96 bg-base-100 shadow-xl p-6 mt-4 mb-4">
4345
<article class="text-center text-4xl font-extrabold">

0 commit comments

Comments
 (0)