|
| 1 | +--- |
| 2 | +name: create-convex-action |
| 3 | +description: Writes Zod-validated Convex actions for external API calls. Consult this skill whenever creating server-side actions with za/zia, calling external APIs from Convex, accessing the database indirectly via runQuery/runMutation, scheduling follow-up functions, or consuming actions from React with useAction. |
| 4 | +--- |
| 5 | + |
| 6 | +# Actions |
| 7 | + |
| 8 | +Write Zod-validated Convex actions for external API calls. Actions run in Node.js and cannot directly access the database. |
| 9 | + |
| 10 | +## Server Side |
| 11 | + |
| 12 | +### Imports |
| 13 | + |
| 14 | +```ts |
| 15 | +import { z } from "zod"; |
| 16 | +import { zx } from "zodvex/core"; |
| 17 | +import { za, zia } from "./utils"; // za = public, zia = internal |
| 18 | +``` |
| 19 | + |
| 20 | +### Public Action |
| 21 | + |
| 22 | +```ts |
| 23 | +export const fetchGitHubRepo = za({ |
| 24 | + args: { owner: z.string(), repo: z.string() }, |
| 25 | + returns: z.object({ |
| 26 | + name: z.string(), |
| 27 | + description: z.string().nullable(), |
| 28 | + stargazers_count: z.number(), |
| 29 | + }), |
| 30 | + handler: async (ctx, { owner, repo }) => { |
| 31 | + const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`); |
| 32 | + if (!response.ok) throw new Error(`GitHub API error: ${response.status}`); |
| 33 | + return await response.json(); |
| 34 | + }, |
| 35 | +}); |
| 36 | +``` |
| 37 | + |
| 38 | +### Internal Action |
| 39 | + |
| 40 | +```ts |
| 41 | +export const sendWebhook = zia({ |
| 42 | + args: { url: z.string().url(), payload: z.record(z.unknown()) }, |
| 43 | + handler: async (ctx, { url, payload }) => { |
| 44 | + await fetch(url, { |
| 45 | + method: "POST", |
| 46 | + headers: { "Content-Type": "application/json" }, |
| 47 | + body: JSON.stringify(payload), |
| 48 | + }); |
| 49 | + }, |
| 50 | +}); |
| 51 | +``` |
| 52 | + |
| 53 | +### Actions with Database Access |
| 54 | + |
| 55 | +Actions cannot access `ctx.db` directly. Use `ctx.runQuery` and `ctx.runMutation`: |
| 56 | + |
| 57 | +```ts |
| 58 | +import { internal } from "./_generated/api"; |
| 59 | + |
| 60 | +export const syncFromGitHub = zia({ |
| 61 | + args: { projectId: zx.id("projects") }, |
| 62 | + handler: async (ctx, { projectId }) => { |
| 63 | + // 1. Read from DB via internal query |
| 64 | + const project = await ctx.runQuery(internal.projects.getById, { id: projectId }); |
| 65 | + if (!project) throw new Error("Project not found"); |
| 66 | + |
| 67 | + // 2. Call external API |
| 68 | + const response = await fetch(`https://api.github.com/repos/${project.fullName}/releases`); |
| 69 | + const releases = await response.json(); |
| 70 | + |
| 71 | + // 3. Write to DB via internal mutation |
| 72 | + for (const release of releases) { |
| 73 | + await ctx.runMutation(internal.releases.upsertFromGitHub, { |
| 74 | + projectId, |
| 75 | + tagName: release.tag_name, |
| 76 | + body: release.body, |
| 77 | + }); |
| 78 | + } |
| 79 | + }, |
| 80 | +}); |
| 81 | +``` |
| 82 | + |
| 83 | +### Scheduling Follow-up Functions |
| 84 | + |
| 85 | +```ts |
| 86 | +export const processWithRetry = zia({ |
| 87 | + args: { taskId: zx.id("tasks"), attempt: z.number().default(1) }, |
| 88 | + handler: async (ctx, { taskId, attempt }) => { |
| 89 | + try { |
| 90 | + // ... external API call |
| 91 | + } catch (error) { |
| 92 | + if (attempt < 3) { |
| 93 | + await ctx.scheduler.runAfter(5000, internal.tasks.processWithRetry, { |
| 94 | + taskId, |
| 95 | + attempt: attempt + 1, |
| 96 | + }); |
| 97 | + } |
| 98 | + } |
| 99 | + }, |
| 100 | +}); |
| 101 | +``` |
| 102 | + |
| 103 | +### Context API |
| 104 | + |
| 105 | +The action `ctx` provides: |
| 106 | +- `ctx.auth` — Authentication info |
| 107 | +- `ctx.runQuery(internal.module.fn, args)` — Call a query |
| 108 | +- `ctx.runMutation(internal.module.fn, args)` — Call a mutation |
| 109 | +- `ctx.runAction(internal.module.fn, args)` — Call another action |
| 110 | +- `ctx.scheduler.runAfter(delay, internal.module.fn, args)` — Schedule a function |
| 111 | +- Full Node.js environment (`fetch`, `crypto`, etc.) |
| 112 | + |
| 113 | +Actions run in Node.js isolation and cannot access `ctx.db` directly. All database access goes through `ctx.runQuery` / `ctx.runMutation`. |
| 114 | + |
| 115 | +### Testing |
| 116 | + |
| 117 | +For action testing patterns including mocking external APIs, consult the `create-convex-test` skill. |
| 118 | + |
| 119 | +## Client Side |
| 120 | + |
| 121 | +Actions are called the same way as mutations from the client: |
| 122 | + |
| 123 | +```ts |
| 124 | +// src/services/github.ts |
| 125 | +import { api } from "@convex"; |
| 126 | +import { useAction } from "convex/react"; |
| 127 | + |
| 128 | +export function useFetchGitHubRepo() { |
| 129 | + return useAction(api.github.fetchGitHubRepo); |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +```tsx |
| 134 | +function ImportRepo() { |
| 135 | + const fetchRepo = useFetchGitHubRepo(); |
| 136 | + |
| 137 | + async function handleImport(owner: string, repo: string) { |
| 138 | + const data = await fetchRepo({ owner, repo }); |
| 139 | + console.log(data.name, data.stargazers_count); |
| 140 | + } |
| 141 | + |
| 142 | + return <button onClick={() => handleImport("vercel", "next.js")}>Import</button>; |
| 143 | +} |
| 144 | +``` |
0 commit comments