NoobyN
Convex Community5mo ago
5 replies
Nooby

Dealing with images

Hi, do you think, it's the good way to deal with images :


import { v } from "convex/values";
import { query } from "./_generated/server";
import { paginationOptsValidator } from "convex/server";
import { R2 } from "@convex-dev/r2";
import { components } from "./_generated/api";

const r2 = new R2(components.r2);

export const listProductsWithImages = query({
  args: { paginationOpts: paginationOptsValidator },
  handler: async (ctx, args) => {
    // Paginate products
    const results = await ctx.db
      .query("products")
      .paginate(args.paginationOpts);

    // For each product in the page, fetch image URLs and sizes
    const page = await Promise.all(
      results.page.map(async (product) => {
        const imageUrls = await Promise.all(
          (product.imageKeys ?? []).map((key) => r2.getUrl(key))
        );
        const imageSizes = await Promise.all(
          (product.imageKeys ?? []).map(async (key) => {
            return await ctx.db
              .query("imageSizes")
              .withIndex("by_image_key", (q) => q.eq("imageKey", key))
              .first();
          })
        );
        return {
          ...product,
          imageUrls,
          imageSizes,
        };
      })
    );

    // Return the paginated result, replacing the page with the enriched data
    return {
      ...results,
      page,
    };
  },
});
Was this page helpful?