Coherent.js Object-Based API Framework Usage Guide
This guide explains how to use the pure object-oriented API framework in Coherent.js, featuring declarative routing, validation, error handling, serialization, and middleware.
Table of Contents
- Object Router
- Error Handling
- Validation
- Serialization
- Middleware
- Pure Node.js HTTP Server Integration
- Security Features
Object Router
The object router provides a pure object-oriented approach to define API routes using nested JavaScript objects.
Basic Usage
import { createRouter } from '@coherent.js/api';
const routes = {
api: {
users: {
get: {
handler: (req, res) => ({ users: [] })
},
post: {
handler: (req, res) => ({ user: { id: 1, name: 'John Doe' } })
},
':id': {
get: {
handler: (req, res) => ({ user: { id: req.params.id, name: 'John Doe' } })
}
}
}
}
};
const router = createRouter(routes);
export default router;HTTP Methods
The object router supports all standard HTTP methods as object keys:
get: { handler: ... }post: { handler: ... }put: { handler: ... }delete: { handler: ... }patch: { handler: ... }
Middleware
You can add middleware to routes using the middleware property:
const routes = {
api: {
users: {
get: {
middleware: [
(req, res, next) => {
console.log('Request received');
next();
}
],
handler: (req, res) => ({ users: [] })
}
}
}
};Error Handling
The API framework provides standardized error classes and handling utilities.
Error Classes
ApiError- Base API error classValidationError- Validation errorAuthenticationError- Authentication errorAuthorizationError- Authorization errorNotFoundError- Not found errorConflictError- Conflict error
Usage
import { ApiError, NotFoundError } from '@coherent.js/api';
const routes = {
api: {
users: {
':id': {
get: {
handler: (req, res) => {
const userId = req.params.id;
if (userId !== '1') {
throw new NotFoundError('User not found');
}
return { user: { id: userId, name: 'John Doe' } };
}
}
}
}
}
};Error Handling Middleware
Error handling is enabled by default in object routes, but you can control it:
const routes = {
api: {
error: {
get: {
errorHandling: true, // enabled by default
handler: async (req, res) => {
// This might throw an error
throw new Error('Something went wrong');
}
}
}
}
};Express Integration
For Express integration, the object router handles errors automatically:
import express from 'express';
import { createRouter } from '@coherent.js/api';
const app = express();
const router = createRouter(routes);
app.use(router.toExpress());Validation
The API framework provides schema-based validation utilities.
Usage
const userSchema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
};
const routes = {
api: {
users: {
post: {
validation: userSchema,
handler: (req, res) => {
// This will only be called if validation passes
const { name, email } = req.body;
return { user: { id: 1, name, email } };
}
}
}
}
};Query and Parameter Validation
You can also validate query parameters and path parameters:
import { withQueryValidation, withParamsValidation } from 'coherent/api';
const querySchema = {
type: 'object',
properties: {
limit: { type: 'number', minimum: 1, maximum: 100 }
}
};
const paramsSchema = {
type: 'object',
properties: {
id: { type: 'string', pattern: '^\d+