|
| 1 | +--- |
| 2 | +name: "Create Validated Function" |
| 3 | +description: Scaffold a function using the validated-function pattern (DI + Zod validation + error handling) |
| 4 | +--- |
| 5 | + |
| 6 | +# Create Validated Function |
| 7 | + |
| 8 | +Create a new function using the validation and error-handling pattern with Zod schemas. |
| 9 | + |
| 10 | +## Pattern Overview |
| 11 | + |
| 12 | +A builder-style approach: |
| 13 | + |
| 14 | +1. **Outer function** (`createXxx`) accepts dependencies as parameters (dependency injection). |
| 15 | +2. **Inner function** (`fn`) contains the actual business logic with typed parameters. |
| 16 | +3. **Wrapper** (`withErrorHandlingAndValidation`) handles validation and errors. |
| 17 | + |
| 18 | +This enables **dependency injection**, making functions easy to test by swapping real |
| 19 | +dependencies with mocks. |
| 20 | + |
| 21 | +## Instructions |
| 22 | + |
| 23 | +1. **Identify or create the Zod schema** in `@qcobro/common`: |
| 24 | + - Check if a schema already exists in `mods/common/src/schemas/`. |
| 25 | + - If not, create a new schema file following the naming convention: `<domain>.ts`. |
| 26 | + - Export the schema and its inferred type from `mods/common/src/schemas/index.ts`. |
| 27 | + - Export from `mods/common/src/index.ts`. |
| 28 | + |
| 29 | +2. **Use existing client interfaces** from `@qcobro/common`: |
| 30 | + - Client interfaces live in `mods/common/src/types/`. |
| 31 | + - Import them: `import type { CustomerClient } from "@qcobro/common"`. |
| 32 | + - If a new interface is needed, add it to the types folder. |
| 33 | + |
| 34 | +3. **Create the function file** following the naming pattern `create<FunctionName>.ts`: |
| 35 | + |
| 36 | + ```typescript |
| 37 | + import { |
| 38 | + withErrorHandlingAndValidation, |
| 39 | + <schemaName>, |
| 40 | + type <InputType>, |
| 41 | + type <ClientType> |
| 42 | + } from "@qcobro/common"; |
| 43 | + |
| 44 | + export function create<FunctionName>(client: <ClientType>) { |
| 45 | + const fn = async (params: <InputType>) => { |
| 46 | + // Business logic here using the injected client |
| 47 | + return client.doSomething(params); |
| 48 | + }; |
| 49 | + |
| 50 | + return withErrorHandlingAndValidation(fn, <schemaName>); |
| 51 | + } |
| 52 | + ``` |
| 53 | + |
| 54 | +4. **Export the function** from the appropriate barrel file or index. |
| 55 | + |
| 56 | +## Example: Customer Operations |
| 57 | + |
| 58 | +### Using Shared Types |
| 59 | + |
| 60 | +```typescript |
| 61 | +import { |
| 62 | + withErrorHandlingAndValidation, |
| 63 | + createCustomerSchema, |
| 64 | + type CreateCustomerInput, |
| 65 | + type CustomerClient |
| 66 | +} from "@qcobro/common"; |
| 67 | + |
| 68 | +export function createCreateCustomer(client: CustomerClient) { |
| 69 | + const fn = async (params: CreateCustomerInput) => { |
| 70 | + return client.customer.create({ data: params }); |
| 71 | + }; |
| 72 | + |
| 73 | + return withErrorHandlingAndValidation(fn, createCustomerSchema); |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +### Production Usage |
| 78 | + |
| 79 | +```typescript |
| 80 | +import { prisma } from "./db.js"; |
| 81 | +import { createCreateCustomer } from "./customers/createCreateCustomer.js"; |
| 82 | + |
| 83 | +// Inject the real database client |
| 84 | +const createCustomer = createCreateCustomer(prisma); |
| 85 | + |
| 86 | +// Validates input and throws ValidationError if invalid |
| 87 | +const customer = await createCustomer({ |
| 88 | + name: "John Doe", |
| 89 | + phone: "+1234567890" |
| 90 | +}); |
| 91 | +``` |
| 92 | + |
| 93 | +## Example: Custom Service Function |
| 94 | + |
| 95 | +The pattern works for any function, not just database operations. |
| 96 | + |
| 97 | +### Schema |
| 98 | + |
| 99 | +```typescript |
| 100 | +// mods/common/src/schemas/notification.ts |
| 101 | +import { z } from "zod"; |
| 102 | + |
| 103 | +export const sendNotificationSchema = z.object({ |
| 104 | + recipient: z.string().email(), |
| 105 | + subject: z.string().min(1), |
| 106 | + body: z.string().min(1), |
| 107 | + priority: z.enum(["low", "normal", "high"]).optional() |
| 108 | +}); |
| 109 | + |
| 110 | +export type SendNotificationInput = z.infer<typeof sendNotificationSchema>; |
| 111 | +``` |
| 112 | + |
| 113 | +### Client Interface |
| 114 | + |
| 115 | +```typescript |
| 116 | +// mods/common/src/types/notification.ts |
| 117 | +import type { SendNotificationInput } from "../schemas/notification.js"; |
| 118 | + |
| 119 | +export interface NotificationClient { |
| 120 | + send(params: SendNotificationInput): Promise<{ messageId: string }>; |
| 121 | +} |
| 122 | +``` |
| 123 | + |
| 124 | +## Testing |
| 125 | + |
| 126 | +Inject a mock client and assert on validation + delegation: |
| 127 | + |
| 128 | +```typescript |
| 129 | +it("throws ValidationError and never calls the client on invalid input", async () => { |
| 130 | + const mockClient = { customer: { create: sinon.stub() } }; |
| 131 | + const createCustomer = createCreateCustomer(mockClient); |
| 132 | + |
| 133 | + try { |
| 134 | + await createCustomer({ name: "" }); |
| 135 | + expect.fail("Expected ValidationError to be thrown"); |
| 136 | + } catch (error) { |
| 137 | + expect(error).to.be.instanceOf(ValidationError); |
| 138 | + expect(mockClient.customer.create.called).to.be.false; |
| 139 | + } |
| 140 | +}); |
| 141 | +``` |
| 142 | + |
| 143 | +Benefits: testability (mocks, no live services), isolation, fast tests, predictable behavior, |
| 144 | +and guaranteed validation coverage (invalid input never reaches the client). |
| 145 | + |
| 146 | +## Error Handling |
| 147 | + |
| 148 | +The `withErrorHandlingAndValidation` wrapper: |
| 149 | + |
| 150 | +- Validates input against the Zod schema using `safeParse`. |
| 151 | +- Throws `ValidationError` with field-level errors if validation fails. |
| 152 | +- Passes validated, typed data to the inner function. |
| 153 | + |
| 154 | +`ValidationError` includes: |
| 155 | + |
| 156 | +- `message`: human-readable message. |
| 157 | +- `fieldErrors`: array of `{ field, message, code }`. |
| 158 | +- `zodError`: original Zod error for debugging. |
| 159 | +- `toJSON()`: serializable form for API responses. |
| 160 | + |
| 161 | +## Files Reference |
| 162 | + |
| 163 | +- Utility: `mods/common/src/utils/withErrorHandlingAndValidation.ts` |
| 164 | +- Error: `mods/common/src/errors/ValidationError.ts` |
| 165 | +- Schemas: `mods/common/src/schemas/` |
| 166 | +- Client interfaces: `mods/common/src/types/` |
0 commit comments