edec is an Express-based TypeScript library that helps to organize and manage Express applications by providing decorators for controllers, routes, error handling, and logging. This library simplifies the process of setting up an Express server and managing its routes and responses.
-
Application Management: Easily create and configure an Express application.
-
Decorator-based Controllers and Routes: Use decorators to define controllers and routes, reducing boilerplate code.
-
Centralized Error Handling: Custom error classes for handling and logging errors.
-
Response Utilities: Utility methods for sending success and error responses.
-
Built-in Logging: Built-in morgan logger for HTTP requests.
Install the package via npm or yarn:
npm install edec
or
yarn add edec
Here’s a quick example of how to use the library to create an Express application, define routes using decorators, and handle HTTP requests.
- Create an Express Application
import { Application } from "edec";
const app = new Application();
app.start(3000, () => {
console.log("Server is running on port 3000");
});
- Define Controllers and Routes
import { Controller, ApiRouter, HttpResponse } from "edec";
/**
* Example controller for handling API requests
*/
const router = new ApiRouter();
@Controller("/users")
class UserController {
@router.get("/")
getUsers() {
HttpResponse.ok({
data: [{ id: 1, name: "John Doe" }],
});
}
@router.post("/")
createUser() {
HttpResponse.created({
data: { id: 1, name: "John Doe" },
});
}
}
// Initialize the controller in the app
const app = new Application();
app.defineRoutes([UserController]);
app.start(3000);
- Error Handling The library provides custom error classes for better error handling and logging.
import { ApiError } from "edec";
try {
// Simulating an error
throw new ApiError("Something went wrong!");
} catch (error) {
error.log(); // Log the error
}
The Application
class is used to create and configure the Express app.
-
getApp()
: Returns the Express application. -
defineRoutes(controllers: any[])
: Registers the routes for the given controllers. -
start(port: number, callback?: () => void)
: Starts the server on the specified port.
-
get(path?: string, ...middlewares: Function[]): MethodDecorator
-
post(path?: string, ...middlewares: Function[]): MethodDecorator
-
put(path?: string, ...middlewares: Function[]): MethodDecorator
-
patch(path?: string, ...middlewares: Function[]): MethodDecorator
-
delete(path?: string, ...middlewares: Function[]): MethodDecorator
-
options(path?: string, ...middlewares: Function[]): MethodDecorator
-
head(path?: string, ...middlewares: Function[]): MethodDecorator
-
create(statusCode: number, data: any): void
-
ok(data: any): void
-
created(data: any): void
-
badRequest(message: string): void
-
unauthorized(message: string): void
-
forbidden(message: string): void
-
notFound(message: string): void
-
internalServerError(message: string): void