@schafevormfenster/rest-commons
v0.1.1
Published
Centralized authority for REST standards and schemas - XSD schemas, parsing functions, and coding instructions
Downloads
105
Readme
@schafevormfenster/rest-commons
Centralized authority for REST API standards and schemas
What is this package?
@schafevormfenster/rest-commons is the central repository for REST API standards, schemas, and utilities used across all @schafevormfenster services. It provides a standardized foundation for building consistent, type-safe REST APIs with built-in validation, security, and best practices.
Think of it as the "XSD for REST APIs" - a single source of truth for API contracts, data structures, and validation rules.
Why does this package exist?
The Problem
Without centralized standards, REST APIs often suffer from:
- Inconsistent response formats across different endpoints
- Duplicated validation logic in multiple services
- Type mismatches between client and server
- Security vulnerabilities from inadequate input validation
- Poor API documentation due to lack of standard structures
- Maintenance burden when response formats need to change
The Solution
This package provides:
- Standardized Response Schemas: Consistent wrappers for all API responses (success, error, collections, health checks)
- Reusable Primitive Schemas: Common data types (UUID, slug, location, timestamps) that work across all services
- Type-Safe Validation: Runtime validation with Zod that automatically generates TypeScript types
- Security Utilities: Input sanitization, suspicious pattern detection, and validation helpers
- Time Handling: Robust ISO 8601 support, relative time parsing, and timezone handling
- Response Utilities: Correlation IDs, standardized headers, and environment detection
What problems does it solve?
1. Response Consistency
Before: Every service defines its own response format
// Service A
{ data: {...}, success: true }
// Service B
{ result: {...}, status: "ok" }
// Service C
{ body: {...}, code: 200 }After: All services use standard response schemas
// All services
{
status: 200,
timestamp: "2024-01-15T10:30:00.000Z",
data: {...}
}2. Type Safety
Before: Manual type definitions that can drift from runtime validation
// Types might not match actual validation
type User = { id: string; name: string };
// Validation is separate and can diverge
const validateUser = (data: any) => { ... };After: Single source of truth with Zod
// Schema and type are always in sync
export const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
});
export type User = z.infer<typeof UserSchema>;3. Code Reusability
Before: Every service implements its own validation
// Service A
function validateUUID(id: string) { ... }
// Service B (duplicate implementation)
function validateUUID(id: string) { ... }After: Import and reuse from commons
import { UuidSchema } from "@schafevormfenster/rest-commons";
const validated = UuidSchema.parse(id);4. Security & Validation
Before: Inconsistent or missing security checks
// Some services check for suspicious patterns, others don'tAfter: Built-in security utilities
import { detectSuspiciousPatterns } from "@schafevormfenster/rest-commons";
if (detectSuspiciousPatterns(userInput)) {
throw new ValidationError("Invalid input detected");
}5. API Documentation
Before: Manual documentation that quickly becomes outdated
## Response Format
Returns a JSON object with...After: Self-documenting schemas
// Schema serves as executable documentation
export const MyResponseSchema = ResultSchema.extend({
data: MyDataSchema,
});
// Automatically generates OpenAPI spec, TypeScript types, and validationWhen should you use this package?
Use @schafevormfenster/rest-commons when you:
- ✅ Build REST APIs in the @schafevormfenster ecosystem
- ✅ Need standardized response formats
- ✅ Want type-safe validation with Zod
- ✅ Require input sanitization and security checks
- ✅ Need to handle ISO 8601 timestamps or relative time
- ✅ Want consistent error handling across services
- ✅ Need correlation IDs for request tracing
Don't use this package if you:
- ❌ Build GraphQL APIs (use appropriate GraphQL schema tools)
- ❌ Work outside the @schafevormfenster ecosystem (fork and adapt instead)
- ❌ Need real-time WebSocket protocols (this is for REST only)
What's included?
Core Response Schemas
- ResultSchema: Single resource responses
- ResultsSchema: Collection responses
- ErrorSchema: Standardized error responses
- HealthSchema: Service health checks
- OkaySchema: Simple success acknowledgments
Primitive Schemas
- UuidSchema: UUID validation
- SlugSchema: URL-safe slugs
- LocationSchema: Geographic locations
- ISO8601Schema: Timestamp validation
- RelativeTimeSchema: Relative time expressions
- And more...
Utilities
- Time Handling: ISO 8601 parsing, relative time, week boundaries
- Validation: Suspicious pattern detection, parameter validation
- Normalization: List normalization, location normalization
- Response Helpers: Correlation IDs, header builders, environment detection
Installation
pnpm add @schafevormfenster/rest-commonsQuick Start
import {
ResultSchema,
ErrorSchema,
UuidSchema,
detectSuspiciousPatterns,
getCorrelationId,
} from "@schafevormfenster/rest-commons";
// Define your data schema
const UserSchema = z.object({
id: UuidSchema,
name: z.string(),
email: z.string().email(),
});
// Create response schema
const UserResponseSchema = ResultSchema.extend({
data: UserSchema,
});
// Use in your API route
export async function GET(request: Request) {
const correlationId = getCorrelationId(request);
// Your business logic here
const user = await fetchUser();
// Validate and return
const response = UserResponseSchema.parse({
status: 200,
timestamp: new Date().toISOString(),
data: user,
});
return Response.json(response);
}Documentation
For detailed implementation guides and best practices, see:
- CONTRIBUTING.md - How to use this package and develop REST endpoints
- REST Service Design Guide - Architectural patterns
- E2E Testing Guide - Testing patterns
- Tech Stack - Technology choices
Key Principles
This package embodies these principles:
- Contract-First Development: Define schemas before implementation
- Type Safety: Runtime validation generates compile-time types
- Consistency: Standardized formats across all services
- Security: Built-in input validation and sanitization
- Observability: Correlation IDs and structured responses
- Developer Experience: Self-documenting, autocomplete-friendly APIs
Tech Stack
This package is built with:
- Zod: Schema validation and type inference
- TypeScript: Type-safe development
- Vitest: Unit testing
- ESLint: Code quality enforcement
Contributing
This package is part of the @schafevormfenster monorepo. For contribution guidelines, see:
- CONTRIBUTING.md - Development guide for this package
- Root monorepo CONTRIBUTING.md - General contribution guidelines
Related Packages
- @schafevormfenster/eslint-plugin: Custom ESLint rules for REST APIs
- @schafevormfenster/eslint-config: ESLint configurations for the monorepo
- @schafevormfenster/logging: Structured logging utilities
- @schafevormfenster/security: Security helpers and utilities
License
See the root LICENSE file for license information.
Built with ❤️ by the Schafe vorm Fenster team
