Files
verse-quote-app/actions/toggle-favorite.ts
T
exe.dev user 0a18c774a5
CI / build (push) Successful in 4m26s
Build Verse: a poem-quote app on the agent-native chat template
Adds a Postgres-backed quotes domain (poems/quotes/favorites) exposed as
five agent-native actions (list-quotes, get-random-quote, create-quote,
toggle-favorite, list-favorites) callable from both chat and the React UI
via useActionQuery/useActionMutation. Moves the primary UI from chat to a
mobile-first Quotes/Favorites experience (chat moves to /chat), adds
manual OpenTelemetry instrumentation exporting traces/metrics/logs over
OTLP, and wires a local Docker Postgres for shared state.
2026-07-25 17:42:04 +00:00

55 lines
1.8 KiB
TypeScript

import { defineAction } from "@agent-native/core/action";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { db, schema } from "../server/db/index.js";
import { quoteFavoriteCounter, withActionSpan } from "../server/otel.js";
export default defineAction({
description:
"Favorite or unfavorite a quote for a given visitor (toggles based on current state). Returns the new favorited state and total favorite count for the quote.",
schema: z.object({
quoteId: z.coerce.number().int().describe("The quote's id"),
visitorId: z.string().min(1).describe("Anonymous visitor id (from browser storage)"),
}),
run: async (args) => {
return withActionSpan(
"toggle-favorite",
{ quoteId: args.quoteId },
async () => {
const existing = await db()
.select()
.from(schema.favorites)
.where(
and(
eq(schema.favorites.quote_id, args.quoteId),
eq(schema.favorites.visitor_id, args.visitorId),
),
)
.limit(1);
let favorited: boolean;
if (existing.length > 0) {
await db().delete(schema.favorites).where(eq(schema.favorites.id, existing[0].id));
favorited = false;
quoteFavoriteCounter.add(1, { action: "remove" });
} else {
await db().insert(schema.favorites).values({
quote_id: args.quoteId,
visitor_id: args.visitorId,
});
favorited = true;
quoteFavoriteCounter.add(1, { action: "add" });
}
const allFavorites = await db()
.select()
.from(schema.favorites)
.where(eq(schema.favorites.quote_id, args.quoteId));
return { quoteId: args.quoteId, favorited, favoriteCount: allFavorites.length };
},
);
},
});