demo-voterindex.ts2 matches
7778// Create new vote
79app.post("/api/votes", async (c) => {
80const id = crypto.randomUUID();
81const title = generateVoteTitle();
9596// Get vote by ID
97app.get("/api/votes/:id", async (c) => {
98const id = c.req.param("id");
99const now = Date.now();
RichardhandleLocation.ts8 matches
3const { lat, lon } = await req.json();
45const openCageKey = Deno.env.get("OPENCAGE_API_KEY");
6const openAIKey = Deno.env.get("OPENAI_API_KEY");
78if (!openCageKey || !openAIKey) {
9return new Response(
10JSON.stringify({ error: "API keys not set in environment variables." }),
11{ status: 500, headers: { "Content-Type": "application/json" } },
12);
15// Reverse geocode to get place name
16const geoResp = await fetch(
17`https://api.opencagedata.com/geocode/v1/json?q=${lat}+${lon}&key=${openCageKey}`,
18);
19const geoData = await geoResp.json();
22// Get Wikipedia summary for the place
23const wikiResp = await fetch(
24`https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(placeName)}`,
25);
26const wikiData = await wikiResp.json();
31`You are Richard Ayoade from Travel Man. Write a short, dry, funny fact about this place:\n\nLocation: ${placeName}\nFact: ${summary}`;
3233// Call OpenAI API for witty fact
34const openaiResp = await fetch("https://api.openai.com/v1/chat/completions", {
35method: "POST",
36headers: {
47const errorText = await openaiResp.text();
48return new Response(
49JSON.stringify({ error: `OpenAI API error: ${errorText}` }),
50{ status: 500, headers: { "Content-Type": "application/json" } },
51);
GetRamiLevySearchmain.tsx2 matches
3export default async function(req: Request): Promise<Response> {
4if (req.method.toLowerCase() !== "post") {
5const response = await axios.post("https://www.rami-levy.co.il/api/catalog", {
6q: "8000380004911",
7aggs: 1,
32}
33const { barcode } = await req.json() as { barcode: string };
34const response = await axios.post("https://www.rami-levy.co.il/api/catalog", {
35q: barcode,
36aggs: 1,
demo-voterknowledge.md14 matches
14- Generate code in TypeScript or TSX
15- Add appropriate TypeScript types and interfaces for all data structures
16- Prefer official SDKs or libraries than writing API calls directly
17- Ask the user to supply API or library documentation if you are at all unsure about it
18- **Never bake in secrets into the code** - always use environment variables
19- Include comments explaining complex logic (avoid commenting obvious operations)
24### 1. HTTP Trigger
2526- Create web APIs and endpoints
27- Handle HTTP requests and responses
28- Example structure:
135## GreenPTClient
136137The `GreenPTClient` is a function that allows interaction with the GreenPT API for chat completions. It accepts a model parameter and provides an `invoke` method to send messages and retrieve responses asynchronously. To ensure API security, it requires an API key stored in environment variables.
138139### Example Usage
146async function getChatResponse() {
147const messages = [
148{ role: "user", content: "What is the capital of France?" },
149];
150153console.log("AI Response:", response);
154} catch (error) {
155console.error("Error invoking GreenPT API:", error);
156}
157}
161```
162163In this example, we create an instance of `GreenPTClient`, send a message asking about the capital of France, and log the AI's response. Error handling is included to catch any issues with the API call.
164165228However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
229If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
230or by making an API request for it.
231232## Val Town Platform Specifics
236- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
237- **Storage:** DO NOT use the Deno KV module for storage
238- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
239- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
240- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
241- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
242- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
243- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
244- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
245- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
279### Backend (Hono) Best Practices
280281- Hono is the recommended API framework
282- Main entry point should be `backend/index.ts`
283- **Static asset serving:** Use the utility functions to read and serve project files:
303});
304```
305- Create RESTful API routes for CRUD operations
306- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
307```ts
340- For files in the project, use `readFile` helpers
3413425. **API Design:**
343- `fetch` handler is the entry point for HTTP vals
344- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
demo-voterREADME.md4 matches
1314- **Frontend**: React with React Query for state management
15- **Backend**: Hono API framework
16- **Database**: SQLite for data persistence
17- **Styling**: TailwindCSS
26Example: "Amsterdam sustainable platform"
2728## API Endpoints
2930- `POST /api/votes` - Create a new vote
31- `GET /api/votes/:id` - Get vote by ID
3233## Data Persistence
demo-voterVotePage.tsx1 match
19queryKey: ["vote", voteId],
20queryFn: async (): Promise<Vote> => {
21const response = await fetch(`/api/votes/${voteId}`);
22
23if (!response.ok) {
demo-voterCreateVote.tsx1 match
16const createVoteMutation = useMutation({
17mutationFn: async (): Promise<VoteResponse> => {
18const response = await fetch("/api/votes", {
19method: "POST",
20headers: {
demo-voteropenai-client.mdc2 matches
15Use GlobalRateLimitedChatOpenAI(model, requestsPerSecond) to enforce a global rate limit on chat completions, suitable for shared or public-facing endpoints.
16Val Town/Platform Notes
17Uses Val Town’s standard SQLite API for persistent storage.
18Designed for server-side use (no browser-specific code).
19No secrets are hardcoded; OpenAI API keys are managed by the OpenAI SDK/environment.
demo-voter.cursorrules10 matches
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
2425- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248});
249```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252```ts
285- For files in the project, use `readFile` helpers
2862875. **API Design:**
288- `fetch` handler is the entry point for HTTP vals
289- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
client-generatorREADME.md4 matches
1# GPT Wrapper Interface
23A Val Town project that provides a web interface for interacting with the GreenPT API through a statically imported GPT wrapper.
45## Project Structure
325. View the AI response
3334## API Endpoints
3536- `GET /` - Main web interface
37- `GET /gpt` - API information
38- `POST /gpt` - Send messages to GPT model
3953This project demonstrates:
54- Static importing of external Val Town modules
55- Hono framework for API routing
56- Val Town utility functions for file serving
57- Clean separation of frontend and backend code