Relevant source files
The following files were used as context for generating this wiki page:
- apps/api/src/common/pipes/zod-validation.pipe.ts
- apps/api/src/context/schemas/context-bodies.ts
- apps/api/src/policies/schemas/policy-bodies.ts
- apps/api/src/risks/schemas/risk-bodies.ts
- apps/api/src/organization/schemas/organization-api-bodies.ts
- apps/api/src/people/schemas/people-bodies.ts
- apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts
Validation schemas are a critical component of the API, serving two primary purposes: ensuring data integrity at runtime and providing clear, machine-readable API specifications for documentation. This system leverages Zod for robust runtime validation within NestJS pipes and ApiBodyOptions from @nestjs/swagger to generate comprehensive OpenAPI documentation.
This dual approach guarantees that incoming data conforms to expected structures and types, preventing common errors and security vulnerabilities, while simultaneously offering developers an accurate and up-to-date reference for API interactions.
Zod Validation Pipe
The ZodValidationPipe is a custom NestJS PipeTransform designed to validate incoming request payloads against a specified Zod schema. This pipe intercepts the request body before it reaches the controller method, ensuring that the data adheres to the defined schema.
How it Works
- Instantiation: The pipe is instantiated with a
ZodSchemaobject, which defines the expected structure and types of the data. - Transformation: The
transformmethod receives the incomingvalue(request body) and attempts to parse it using the providedZodSchema. - Error Handling: If the
schema.parse()operation fails (meaning thevaluedoes not conform to the schema), aBadRequestExceptionis thrown, immediately stopping the request processing and returning a 400 Bad Request error to the client. If successful, the parsed (and potentially type-coerced) value is returned.
This pipe ensures that only valid data structures proceed to the business logic layer, enhancing API reliability and security.
import {
ArgumentMetadata,
BadRequestException,
PipeTransform,
} from '@nestjs/common';
import { ZodSchema } from 'zod';
export class ZodValidationPipe implements PipeTransform {
constructor(private schema: ZodSchema) {}
transform(value: unknown, metadata: ArgumentMetadata) {
try {
const parsedValue = this.schema.parse(value);
return parsedValue;
} catch (error) {
throw new BadRequestException('Validation failed');
}
}
}Sources: apps/api/src/common/pipes/zod-validation.pipe.ts:1-17
Validation Flow
The following diagram illustrates the data flow through the ZodValidationPipe:
API Body Schemas for Documentation
In addition to runtime validation, the API utilizes ApiBodyOptions from @nestjs/swagger to define the structure of request bodies for OpenAPI documentation. These schemas are crucial for generating interactive API documentation (e.g., Swagger UI) that clearly outlines expected input formats, types, and examples.
These ApiBodyOptions are typically exported as constants in dedicated *-bodies.ts files and are referenced in controller methods using the @ApiBody() decorator.
Common Structure
Most API body schemas follow a pattern of defining ApiBodyOptions for create and update operations, often referencing specific Data Transfer Objects (DTOs).
import type { ApiBodyOptions } from '@nestjs/swagger';
// ... import DTOs
export const ENTITY_BODIES: Record<string, ApiBodyOptions> = {
createEntity: {
description: 'Entity creation data',
type: CreateEntityDto,
},
updateEntity: {
description: 'Entity update data',
type: UpdateEntityDto,
},
};Detailed Schema Definitions
Context Schemas
The CONTEXT_BODIES object defines ApiBodyOptions for creating and updating context entries, providing detailed examples for Swagger documentation.
export const CONTEXT_BODIES: Record<string, ApiBodyOptions> = {
createContext: {
description: 'Context entry data',
type: CreateContextDto,
examples: {
'Authentication Context': { /* ... */ },
'Database Context': { /* ... */ },
},
},
updateContext: {
description: 'Partial context entry data to update',
type: UpdateContextDto,
examples: {
'Update Tags': { /* ... */ },
'Update Answer': { /* ... */ },
},
},
};Sources: apps/api/src/context/schemas/context-bodies.ts:4-39
Policy Schemas
POLICY_BODIES defines the expected request bodies for policy creation and updates.
export const POLICY_BODIES: Record<string, ApiBodyOptions> = {
createPolicy: {
description: 'Policy creation data',
type: CreatePolicyDto,
},
updatePolicy: {
description: 'Policy update data',
type: UpdatePolicyDto,
},
};Sources: apps/api/src/policies/schemas/policy-bodies.ts:4-13
Risk Schemas
RISK_BODIES specifies the request body structures for creating and updating risks.
export const RISK_BODIES: Record<string, ApiBodyOptions> = {
createRisk: {
description: 'Risk creation data',
type: CreateRiskDto,
},
updateRisk: {
description: 'Risk update data',
},
};Sources: apps/api/src/risks/schemas/risk-bodies.ts:4-13
Organization Schemas
The organization module uses specific ApiBodyOptions for updating organization details and transferring ownership. These schemas define properties directly rather than referencing DTOs.
UPDATE_ORGANIZATION_BODY
| Property | Type | Description | Example |
|---|---|---|---|
name | string | Organization name | New Acme Corporation |
slug | string | Organization slug | new-acme-corp |
logo | string | Organization logo URL | https://example.com/logo.png |
metadata | string | Additional metadata in JSON format | {"theme": "dark"} |
website | string | Organization website URL | https://acme-corp.com |
onboardingCompleted | boolean | Whether onboarding is completed | true |
hasAccess | boolean | Whether organization has access to platform | true |
fleetDmLabelId | integer | FleetDM label ID for device management | 123 |
isFleetSetupCompleted | boolean | Whether FleetDM setup is completed | false |
primaryColor | string | Organization primary color in hex format | #3B82F6 |
Sources: apps/api/src/organization/schemas/organization-api-bodies.ts:4-58
TRANSFER_OWNERSHIP_BODY
| Property | Type | Description | Example | Required |
|---|---|---|---|---|
newOwnerId | string | Member ID of the new owner | mem_xyz789 | Yes |
userId | string | User ID of the current owner initiating the transfer (required for API key auth, ignored for JWT auth) | usr_abc123def456 | No |
Sources: apps/api/src/organization/schemas/organization-api-bodies.ts:60-78
People Schemas
PEOPLE_BODIES defines schemas for creating single members, bulk creating members, and updating member information.
export const PEOPLE_BODIES: Record<string, ApiBodyOptions> = {
createMember: {
description: 'Member creation data',
type: CreatePeopleDto,
},
bulkCreateMembers: {
description: 'Bulk member creation data',
type: BulkCreatePeopleDto,
},
updateMember: {
description: 'Member update data',
type: UpdatePeopleDto,
},
};Sources: apps/api/src/people/schemas/people-bodies.ts:6-19
Task Template Schemas
TASK_TEMPLATE_BODIES provides the schema for updating task templates within the framework editor.
export const TASK_TEMPLATE_BODIES = {
updateTaskTemplate: {
type: UpdateTaskTemplateDto,
description: 'Update framework editor task template data',
},
};Sources: apps/api/src/framework-editor/task-template/schemas/task-template-bodies.ts:3-7
Relationship between ApiBodyOptions and DTOs
ApiBodyOptions often reference DTO (Data Transfer Object) classes to describe the expected request body. This provides a clear link between the runtime data structure (defined by the DTO) and its documentation representation.
Overall API Request Processing with Validation
The following diagram illustrates how validation schemas fit into the broader API request processing pipeline, from client request to response.
On This Page
Zod Validation PipeHow it WorksValidation FlowAPI Body Schemas for DocumentationCommon StructureDetailed Schema DefinitionsContext SchemasPolicy SchemasRisk SchemasOrganization SchemasUPDATE_ORGANIZATION_BODYTRANSFER_OWNERSHIP_BODYPeople SchemasTask Template SchemasRelationship between ApiBodyOptions and DTOsOverall API Request Processing with Validation