chore: Update getBackgroundImages to use getObjectUrl for generating image URLs

This commit is contained in:
Sean Morley
2024-06-12 17:49:26 +00:00
parent 6385f9f46b
commit 5d0b450429
5 changed files with 52 additions and 42 deletions

View File

@@ -1,20 +1,29 @@
import { eq } from "drizzle-orm";
import { db } from "./db.server";
import { imagesTable } from "./schema";
import { getObjectUrl, s3Client } from "$lib/server/s3";
import { ListObjectsV2Command } from "@aws-sdk/client-s3";
export const getBackgroundImages = async (numberOfResults: number | null) => {
const images = await db
.select({ url: imagesTable.url })
.from(imagesTable)
.where(eq(imagesTable.type, "background"))
.execute();
export const getBackgroundImages = async () => {
// const images = await db
// .select({ url: imagesTable.url })
// .from(imagesTable)
// .where(eq(imagesTable.type, "background"))
// .execute();
if (numberOfResults) {
let randomIndex = Math.floor(Math.random() * images.length);
return images.slice(randomIndex, randomIndex + numberOfResults) as {
url: string;
}[];
}
// list all objects in the bucket using listObjectsV2
const data = await s3Client.send(
new ListObjectsV2Command({ Bucket: "images" })
);
const randomImages = data.Contents?.map((item) => item.Key) ?? [];
const randomIndex = Math.floor(Math.random() * randomImages.length);
return images as { url: string }[];
const randomImage = randomImages[randomIndex];
console.log(randomImage);
const url = getObjectUrl("images", randomImage as string);
console.log(url);
return url as string;
};