Skip to content

Commit

Permalink
Merge pull request #18 from ethanniser/cache-search
Browse files Browse the repository at this point in the history
cache search results in kv
  • Loading branch information
ethanniser authored Oct 20, 2024
2 parents 1308842 + 8765f4f commit 60d83ef
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@vercel/analytics": "^1.3.1",
"@vercel/blob": "^0.25.1",
"@vercel/functions": "^1.4.2",
"@vercel/kv": "^3.0.0",
"@vercel/postgres": "^0.10.0",
"@vercel/speed-insights": "^1.0.12",
"bcryptjs": "^2.4.3",
Expand Down
14 changes: 14 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 29 additions & 1 deletion src/lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
subcollection,
} from "../db/schema";
import { getCart, updateCart } from "./cart";
import { kv } from "@vercel/kv";
import { z } from "zod";

export async function addToCart(prevState: unknown, formData: FormData) {
const prevCart = await getCart();
Expand Down Expand Up @@ -60,7 +62,29 @@ export async function removeFromCart(formData: FormData) {
await updateCart(newCart);
}

const searchResultSchema = z.array(
z.object({
href: z.string(),
name: z.string(),
slug: z.string(),
image_url: z.string().nullable(),
description: z.string(),
price: z.string(),
subcategory_slug: z.string(),
}),
);

export async function searchProducts(searchTerm: string) {
const kvKey = `search:${searchTerm}`;

const rawCachedResults = await kv.get(kvKey);
const parsedCachedResults = searchResultSchema.safeParse(rawCachedResults);
if (parsedCachedResults.success) {
return parsedCachedResults.data;
}

// cache miss, run the search

let results;

if (searchTerm.length <= 2) {
Expand Down Expand Up @@ -111,11 +135,15 @@ export async function searchProducts(searchTerm: string) {
);
}

return results.map((item) => {
const searchResults = results.map((item) => {
const href = `/products/${item.categories.slug}/${item.subcategories.slug}/${item.products.slug}`;
return {
...item.products,
href,
};
});

await kv.set(kvKey, searchResults, { ex: 60 * 60 }); // 1 hour

return searchResults;
}

0 comments on commit 60d83ef

Please sign in to comment.