ts-express-generic
v0.0.10
Published
A generic TypeScript controller and service response types for Express
Maintainers
Readme
Express TypeScript Controller Library
A type-safe Express controller library for Node.js with robust type validation and structured service responses.
Features
- 🛡️ Type-safe request processing (body, params, query, headers, locals)
- 🚦 Comprehensive HTTP status codes (2xx, 4xx, 5xx) with type-safe mappings
- 📦 Structured service responses (success/error formats)
- 🧩 Express middleware compatibility
- ⚡ Built-in error handling
Installation
npm install express-ts-controllerQuick Start
import express from 'express';
import {
genericController,
ServiceResponse,
HTTPStatusMap
} from 'express-ts-controller';
const app = express();
app.use(express.json());
// Example service function
const userService = async (input: ): Promise<ServiceResponse> => ({
status: 'OK',
message: 'User found',
data: {
id: input.params.id,
authUserId: input.locals.userId
}
});
app.get('/users/:id',
genericController({
requestKeys: ['params', 'locals'],
middlewares: [authMiddleware],
service: userService
})
);
app.listen(3000);Core Concepts
Controller Configuration
type ControllerConfig<T extends TAllowedRequestKeys, R extends TExtractedRequest<T>> = {
service: ServiceFunction<R, ServiceResponse>;
requestKeys: T[];
middlewares: RequestHandler[];
};Service Responses
Success Response:
{
status: 'OK' | 'CREATED' | ..., // TGoodStatus values
message: string,
data?: unknown
}Error Response:
{
status: 'BAD_REQUEST' | 'INTERNAL_SERVER_ERROR' | ..., // TBadStatus/TServerStatus values
message: string,
error: unknown
}HTTP Status Codes
Access status codes directly or via helper function:
import { HTTPStatusMap, getHTTPStatus } from 'express-ts-controller';
console.log(HTTPStatusMap.NOT_FOUND); // 404
console.log(getHTTPStatus('UNAUTHORIZED')); // 401API Reference
genericController(config)Parameters:
| Key | Type | Description |
| :---------- | :--------- | :------------------------------------------ |
| service | ServiceFunction | Core business logic function |
| requestKeys | TAllowedRequestKeys[] | Request parts to extract (e.g., ['body', 'params']) |
| middlewares | RequestHandler[] | Express middlewares to apply |
Type Exports
// Request handling
type TAllowedRequestKeys = "body" | "params" | "query" | "headers" | "locals";
type TExtractedRequest<T extends TAllowedRequestKeys> = ...;
// HTTP Status
type TGoodStatus = keyof typeof HTTPGoodStatus;
type TBadStatus = keyof typeof HTTPBadStatus;
type TServerStatus = keyof typeof HTTPServerErrorStatus;
// Service functions
type ServiceFunction<TInput, TResponse> = (input: TInput) => Promise<TResponse>;Error Handling
The controller automatically catches errors and forwards them to Express error middleware:
// Example error handler
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
res.status(HTTPStatusMap.INTERNAL_SERVER_ERROR).json({
status: 'INTERNAL_SERVER_ERROR',
message: 'Unexpected server error',
error: error.message
});
});Best Practices
Validation Middleware: Validate requests before controller handling
Type Safety: Always type your service inputs and responses
Status Codes: Use appropriate HTTP status codes from HTTPStatusMap
Error Formatting: Maintain consistent error responses across services
Contributing
Fork the repository
Create your feature branch (git checkout -b feature/amazing-feature)
Commit your changes (git commit -m 'Add amazing feature')
Push to the branch (git push origin feature/amazing-feature)
Open a Pull Request
License
Distributed under the MIT License. See LICENSE for more information.
