Files
ghbot/.agents/skills/zod/references/parse-async-for-async-refinements.md
T
lezi-fun 9e47ab339e feat: sync ghbot-Nodeloc v1.2.0 capabilities into upstream
Merges all 33 commits from lza6/ghbot-Nodeloc (v1.0.0 through v1.2.0)
while keeping both sides' features in every conflicted file:

- EventRouter dispatch extracted from runReview.ts (7.1), with the
  runtime environment block preserved on the review-start comment
- Unified command ack messages (6.3) combined with the collapsed
  runtime environment block and bot signature on /recheck replies
- Status banner and collapsible unposted findings in review bodies (6.1)
- Centralized runtime directories behind GHBOT_RUNTIME_DIR (D-13);
  webhook knowledge cache now lives under tempRootDirectory()
- Production hardening for merge races, timeouts, webhook ops;
  atomic temp-file rename for R2 cache restores kept from upstream
- Webhook parity retained: triage events gated by WEBHOOK_TRIAGE_ENABLED,
  read-only command guidance, repository knowledge injection,
  runtime environment block on webhook chat replies
- Sanitization/secret redaction centralization, error-aware retry,
  duplicate merge prevention, in-process webhook retries, /metrics
- Infra: eslint/prettier gates with CI verify workflow, docs archives

typecheck, eslint, prettier format:check, and 164 tests all pass.
2026-08-24 11:47:28 +08:00

128 lines
3.1 KiB
Markdown

---
title: Use parseAsync for Async Refinements
impact: CRITICAL
impactDescription: Using parse() with async refinements throws an error; async validation silently fails or crashes the application
tags: parse, async, parseAsync, refinement
---
## Use parseAsync for Async Refinements
If your schema uses `refine()` or `superRefine()` with async validation (like database lookups), you must use `parseAsync()` or `safeParseAsync()`. Using synchronous `parse()` with async refinements throws an error.
**Incorrect (sync parse with async refinement):**
```typescript
import { z } from "zod";
const userSchema = z
.object({
email: z.string().email(),
username: z.string().min(3)
})
.refine(
async (data) => {
// Async database check
const exists = await db.users.findByEmail(data.email);
return !exists;
},
{ message: "Email already registered" }
);
// This throws an error!
const user = userSchema.parse(formData);
// Error: Async refinement encountered during synchronous parse operation.
// Use .parseAsync instead.
```
**Correct (using parseAsync):**
```typescript
import { z } from "zod";
const userSchema = z
.object({
email: z.string().email(),
username: z.string().min(3)
})
.refine(
async (data) => {
const exists = await db.users.findByEmail(data.email);
return !exists;
},
{ message: "Email already registered" }
);
// Use parseAsync for async refinements
const user = await userSchema.parseAsync(formData);
// Or safeParseAsync for error handling
const result = await userSchema.safeParseAsync(formData);
if (!result.success) {
console.log(result.error.issues);
}
```
**Async transforms also require parseAsync:**
```typescript
const enrichedUserSchema = z
.object({
userId: z.string().uuid()
})
.transform(async (data) => {
// Async data enrichment
const user = await db.users.findById(data.userId);
return {
...data,
email: user.email,
name: user.name
};
});
// Must use parseAsync
const enrichedUser = await enrichedUserSchema.parseAsync({ userId: "123" });
```
**Pattern for API routes:**
```typescript
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";
const registerSchema = z
.object({
email: z.string().email(),
password: z.string().min(8)
})
.superRefine(async (data, ctx) => {
const existingUser = await db.users.findByEmail(data.email);
if (existingUser) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["email"],
message: "Email already registered"
});
}
});
export async function POST(req: NextRequest) {
const body = await req.json();
// Always use safeParseAsync with async schemas
const result = await registerSchema.safeParseAsync(body);
if (!result.success) {
return NextResponse.json({ errors: result.error.issues }, { status: 400 });
}
// Proceed with registration
}
```
**When NOT to use this pattern:**
- Schemas with only synchronous validation (use parse/safeParse)
- When async validation can be moved outside Zod (validate, then check)
Reference: [Zod API - parseAsync](https://zod.dev/api#parseasync)