0.0.1 • Published 7 months ago
schema-guardian v0.0.1
🛡️ Schema Guardian
Smart schema validation and data transformation for resilient API handling.
Why Schema Guardian?
- 🔄 Handle inconsistent API responses gracefully
- 🛠️ Transform and normalize data on the fly
- 🚨 Recover from validation errors intelligently
- 📝 Detailed error reporting for debugging
- 🎯 Type-safe with full TypeScript support
📦 Installation
npm install schema-guardian
🚀 Quick Start
import { createGuardian } from "schema-guardian";
// Define your schema for API response
const apiResponseSchema = {
data: {
type: "object",
required: true,
schema: {
userId: {
type: "string",
transform: (v) => String(v), // Handle numeric IDs from API
},
email: {
type: "string",
required: true,
validate: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
transform: (v) => v.toLowerCase(), // Normalize emails
},
status: {
type: "string",
allowedValues: ["active", "inactive"],
fallback: "inactive", // Recovery value for invalid status
},
},
},
metadata: {
type: "object",
required: false,
schema: {
timestamp: {
type: "string",
transform: (v) => new Date(v).toISOString(), // Normalize dates
},
},
},
};
// Create guardian instance
const guardian = createGuardian(apiResponseSchema, {
mode: "lenient", // Handle extra fields from API
errorHandling: "recover", // Try to recover from errors
});
// Process API response
const result = guardian.process({
data: {
userId: 12345, // Number instead of string
email: "USER@EXAMPLE.COM", // Uppercase email
status: "ACTIVE", // Wrong case
extraField: "will be stripped", // Unknown field
},
metadata: {
timestamp: "2024-01-10T00:00:00Z",
},
});
console.log(result);
// Output: Normalized and validated data
🛠️ Key Features
Intelligent Recovery
- Automatic fallback values for invalid data
- Custom recovery strategies per field
- Graceful handling of missing data
Smart Transformations
- Type coercion when possible
- Data normalization
- Custom transformation functions
Flexible Validation
- Strict or lenient mode
- Nested object validation
- Array validation with item constraints
- Custom validation rules
Error Handling
- Detailed error messages
- Path information for nested errors
- Recovery attempt tracking
📖 Practical Examples
Handle Inconsistent API Data
const schema = {
user: {
type: "object",
required: true,
schema: {
id: {
type: "string",
transform: (v) => String(v), // Handle numeric IDs
},
name: {
type: "string",
transform: (v) => v?.trim(), // Handle extra spaces
},
settings: {
type: "object",
fallback: { theme: "default" }, // Default for missing data
schema: {
theme: {
type: "string",
allowedValues: ["light", "dark", "default"],
},
},
},
},
},
};
Custom Recovery Strategy
const guardian = createGuardian(schema);
// Add custom recovery for invalid data
guardian.setRecoveryStrategy("user.settings", (invalidValue) => ({
theme: "default",
_recovered: true,
}));
⚙️ Configuration
const guardian = createGuardian(schema, {
mode: "lenient", // Handle extra fields from API
logging: true, // Debug validation process
errorHandling: "recover", // Attempt to recover from errors
trimStrings: true, // Automatically trim strings
coerceTypes: true, // Try to convert types when possible
});