メインコンテンツまでスキップ
バージョン: 🚧 Canary

🎯 Overriding Existing Schemas

This guide demonstrates how to override and extend existing Nodeblocks schemas to customize validation rules, add new fields, or modify existing field constraints. We'll show how to extend the built-in userSchema with custom validation rules and additional required fields.


🏗️ Schema Override Architecture

Schema overriding allows you to:

  1. Extend existing schemas - Build upon pre-defined schemas from the SDK
  2. Add custom validation - Implement domain-specific validation rules
  3. Modify field constraints - Change min/max values, patterns, or types
  4. Control required fields - Make fields required or optional as needed

1️⃣ Understanding Built-in Schemas

Nodeblocks provides pre-built schemas for common entities. The userSchema includes standard user fields:

// Built-in userSchema structure
{
type: 'object',
properties: {
email: { type: 'string' },
name: { type: 'string' },
status: { type: 'string' }
// ... other built-in properties
},
additionalProperties: false
}

2️⃣ Basic Schema Override

Here's how to override an existing schema with custom validation:

src/schemas/customUserSchema.ts
import {
primitives,
schemas,
} from '@nodeblocks/backend-sdk';

const { withSchema } = primitives;
const { userSchema } = schemas;

export const createUserSchema = withSchema({
requestBody: {
content: {
'application/json': {
schema: {
// Spread the existing schema
...userSchema,
properties: {
// Spread existing properties
...userSchema.properties,
// Override or add new properties
age: {
type: 'number',
minimum: 18,
maximum: 100,
}
},
// Make age required in addition to existing required fields
required: ['age'],
},
},
},
required: true,
},
});

3️⃣ Schema Override Patterns

Pattern 1: Adding Fields

// Add new optional fields
schema: {
...existingSchema,
properties: {
...existingSchema.properties,
newField: { type: 'string' }
}
}

Pattern 2: Making Fields Required

// Make existing optional fields required
schema: {
...existingSchema,
required: [...(existingSchema.required || []), 'existingField']
}

Pattern 3: Overriding Field Constraints

// Override existing field with stricter validation
properties: {
...existingSchema.properties,
email: {
...existingSchema.properties.email,
pattern: '^[company-domain]@company\\.com$'
}
}

Pattern 4: Removing Fields

// Remove fields by destructuring
const { unwantedField, ...allowedProperties } = existingSchema.properties;
schema: {
...existingSchema,
properties: allowedProperties
}

➡️ Next Steps

Now you can enhance your schemas by:

  • Adding custom validation rules - Implement business-specific constraints
  • Creating reusable schema components - Build a library of common schema patterns
  • Implementing complex validation - Use conditional schemas and custom validators
  • Testing schema validation - Create comprehensive test suites for your overrides

🔗 See Also