nonlinear-xyz/factory-kit/factory-api
Claude Code and agent skill by nonlinear-xyz/factory-kit
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
API conventions for both server actions and tRPC builds. Covers the decision between them, per-mutation Zod input schemas, central router composition, pagination shape, multi-field search via Drizzle `ilike` + `or()`, mutation lifecycle hooks, conditional query enabling, stale-time defaults, error response shape and custom error class taxonomy, mutation-boundary audit logging, fetch adapter for tRPC routes. Read when designing or implementing any data-mutation endpoint.
Install
npx vskill@latest install nonlinear-xyz/factory-kit/factory-apiSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as nonlinear-xyz/factory-kit/factory-api.
Factory api
Each section leads with Principle (one sentence, stack-agnostic), then Why (constraint → option → tradeoff), then Recipe (the Next.js / Drizzle / tRPC shape we use), and Failure mode when there's one to name. Sections that are pure style with no deeper truth are marked Recipe only. Editors: if the Principle could appear unchanged in Clean Code, sharpen the Why with a Factory-specific observation or drop the section to Recipe only — honesty over inflation.
API style — pick one
Principle. Pick one transport style per project; don't mix server actions and tRPC.
Why. Two transport styles in one codebase means two error-handling conventions, two cache-invalidation patterns, two surfaces to audit. The cost compounds linearly with every new endpoint; the cleanup is almost never worth the disruption. The decision is cheap at project start and expensive six months in.
Recipe.
| Style | Pick when | |
|---|---|---|
| Server actions | Default. Feature-folder colocation matters. One frontend consumer. App-internal API only. Pairs with TanStack Query useMutation. | |
| tRPC | ≥3 entities with cross-feature queries. Multiple frontend consumers. Need typed RPC across a real network boundary. | |
| REST / OpenAPI | Only when an external system needs to call you. Don't use for internal app traffic. |
Failure mode. Encode imported tRPC at project start and built the rest in server actions; the unused tRPC surface created confusion at every call site for months before being deleted.
Server actions — canonical shape
Principle. Every mutation: parse input first, then wrap with org context, then fire-and-forget the audit log.
Why. Three contracts in tension. Validation is the boundary guarantee — past safeParse, downstream code assumes the shape. Org context is the tenant guarantee — without it, a cross-tenant write is one missing filter away. Audit is the reconstructability guarantee — but it's after-the-fact, so it never blocks the response. The order matters: validation can refuse; org context can refuse; audit can fail silently.
Recipe.
Result type is a discriminated union — client checks if ('error' in result).
TanStack Query hook wrapping the action
Principle. Invalidate at the 2-segment query-key prefix, not the individual key.
Why. A list query and a detail query for the same entity share the same invalidation trigger — a mutation invalidates both. Per-key invalidation means writing the prefix twice and forgetting one. Prefix invalidation hits both with one call and stays correct as the entity grows new views.
Recipe.
tRPC — central router composition
Principle. Manual registration over automagic discovery.
Why. A grep-able surface area beats an auto-discovery convention. Every new domain is one diff line that names itself. "Where are all the routers?" answered by reading one file. The cost of one explicit line per domain is trivial; the cost of an implicit auto-discovery scheme is one debugging session per onboarding.
Recipe.
Procedure tiers — stacked
Principle. Stack permission tiers by extension, not by independent definition.
Why. Procedure tiers are an additive permission graph: every authenticated procedure also passes the public middleware; every org-scoped procedure also passes the auth middleware. Building each tier by extending the prior one makes the chain visible at the definition site and impossible to drift. Building each tier independently means duplicated middleware that diverges silently.
Recipe.
See factory-auth.md for the middleware shapes.
Failure mode. Ford-analysis: every procedure defined as publicProcedure. Auth checks lived inside each handler and drifted. Three procedures shipped without auth before someone noticed.
Per-mutation Zod input
Principle. One Zod schema per mutation; colocate with the router.
Why. Mutations diverge in shape long before they look like they will — create needs fields update doesn't, update allows partial input create can't. A shared schema with .optional() everywhere becomes a parse layer that enforces nothing. Per-mutation schemas keep each contract sharp. Colocation means refactoring the mutation refactors the schema in the same diff.
Recipe.
Schemas live next to the router, not in a separate file — unless shared with the client form, in which case see factory-forms.md on the three-variant pattern.
Pagination — limit/offset/orderBy
Principle. Offset pagination by default; cursor only when offset actually breaks.
Why. Offset gives jump-to-page-N at no additional state cost and keeps client state to a single integer. Cursor breaks that affordance, requires more client state, and only pays off past ~100K rows or on append-only feeds. Defaulting to cursor is paying the complexity tax without ever needing the scale.
Recipe.
Cothon uses cursor for chat messages — append-only, never-jump-to-page. That's the right case for cursor.
Multi-field search — ilike + or()
Principle. Start with ilike over the obvious fields; promote to full-text search only when search becomes the bottleneck.
Why. Full-text search is real infrastructure — tsvector indexes, query parsers, ranking. At 10K rows ilike works fine. At 1M rows the upgrade is forced and you'll have the row count to justify it. Reaching for tsvector at 1K rows is engineering against a workload that doesn't exist yet.
Recipe.
Aggregated stats in list queries
Principle. If the list view shows a count, the list query returns the count.
Why. A list page that issues one row-level "fetch count" per visible row is N+1 in slow motion — works fine at 10 rows, falls over at 100. A single aggregated query with leftJoin + groupBy returns the same data in one round trip. The cost is one slightly-longer SQL statement; the savings are linear in row count.
Recipe.
For N+1-prone aggregations on detail views, use a subquery (see factory-data-layer.md).
Mutation lifecycle hooks
Principle. Specify onSuccess; let errors propagate to the boundary.
Why. Per-call-site error handling is duplication that ages badly — every new mutation adds another copy of the toast-on-error pattern. A global error boundary catches what falls through; onSuccess carries the per-mutation specifics (which key to invalidate, which drawer to close). The boundary handles the policy; the hook handles the local action.
Recipe.
For server actions with ActionResult<T> shape, error-handling lives in onSuccess (the discriminated-union check). For tRPC mutations, errors throw — handle via onError or React Error Boundary.
Conditional query enabling
Principle. Gate a dependent query with enabled; never let it fire with undefined arguments.
Why. A query that fires with undefined arguments either errors at the server, returns garbage, or — worst — returns a successful response for "all rows" because the filter silently dropped. enabled makes the dependency declarative and removes the failure mode.
Recipe.
Stale time defaults
Principle. Pick a baseline staleTime at the QueryClient; bump per-query for stable reference data.
Why. Per-query staleTime decisions in every hook is friction that compounds — every new query is another stale-time call. A 60s baseline catches most cases; opt into longer only when the data genuinely doesn't change. staleTime: Infinity is a different design — invalidation becomes the only refresh path, so one missed invalidation is permanent stale state.
Recipe.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/factory-api/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/nonlinear-xyz/factory-kit/factory-api)