tranxpress
Version:
A smart async wrapper for Express with MongoDB transaction support.
244 lines (171 loc) โข 5.11 kB
Markdown
# ๐ง tranxpress
An elegant, extensible, and **fully TypeScript-supported** async handler utility for Express.js that simplifies error handling, supports **MongoDB transactions**, and allows **nested error handlers** for next-level control.
## ๐ Features
- ๐ Wrap async/await routes and middlewares without try-catch hell.
- ๐งฉ Optional MongoDB transactions using Mongoose sessions.
- ๐ Nested `asyncHandler` support (yes, recursion like a boss).
- ๐ Smart MongoDB error parsing with stack trace and error code support.
- ๐ ๏ธ Plug-in custom error handlers at any depth.
- โ
Built-in TypeScript typings for safety and autocompletion bliss.
- ๐ฆ Includes extendable `ErrorResponse` and `SuccessResponse` classes.
## ๐ฆ Installation
```bash
npm install tranxpress
```
If you're using TypeScript and Express:
```bash
npm install --save-dev @types/express
```
## ๐งโ๐ป Usage
### Basic Example
```ts
import express from "express";
import { asyncHandler } from "tranxpress";
const app = express();
app.get(
"/ping",
asyncHandler(async (req, res) => {
// simulate async error
throw new Error("Boom ๐ฅ");
})
);
```
## ๐ผ With MongoDB Transaction (Mongoose)
```ts
app.post(
"/create-user",
asyncHandler(async (req, res) => {
const session = req.session;
const user = await User.create([{ name: "iBoon" }], { session });
res.json({ user });
}, { useTransaction: true })
);
```
> `req.session` is automatically injected if `useTransaction` is true.
## ๐งฌ Nested Error Handlers
You can define a hierarchy of error handlers using `asyncHandler` recursively.
```ts
const deepestHandler = asyncHandler(async (err, req, res) => {
console.log("๐ฅ Deep nested handler:", err.message);
});
const middleHandler = asyncHandler(async (err, req, res) => {
console.log("๐งฉ Middle layer handling error...");
throw err; // pass to next handler
}, { customErrorHandler: deepestHandler });
app.get(
"/crash",
asyncHandler(async (req, res) => {
throw new Error("Nested Boom ๐ฃ");
}, { customErrorHandler: middleHandler })
);
```
## ๐ฆ Advanced MongoDB Error Handling
The package includes a robust `MongoHandledError` wrapper class.
```ts
throw new MongoHandledError(originalMongoError);
```
It parses common errors like:
- `ValidationError` โ 400
- `CastError` โ 400
- `MongoServerError` โ 500
- `DuplicateKeyError` (code `11000`) โ 409
The error contains:
```ts
{
message: "Duplicate key error",
statusCode: 409,
stack: "...",
code: 11000
}
```
## ๐งฐ API Reference
### `asyncHandler(fn, options?)`
| Param | Type | Description |
|----------------------------|-----------------------------|---------------------------------------------|
| `fn` | `(req, res, next) => {}` | The async route/controller function |
| `options.useTransaction` | `boolean` | Enable MongoDB transaction (Mongoose) |
| `options.customErrorHandler` | `AsyncFn` | Another asyncHandler or custom error logic |
## โ
Response Classes
### `ErrorResponse`
Use this to throw custom errors.
```ts
import { ErrorResponse } from "tranxpress";
throw new ErrorResponse("Invalid input", 400, { field: "email" });
```
You can extend it:
```ts
class CustomError extends ErrorResponse {
constructor(message: string) {
super(message, 422);
}
}
```
### `SuccessResponse`
Use this for consistent success responses.
```ts
import { SuccessResponse } from "tranxpress";
res.status(200).json(new SuccessResponse("User created", { user }));
```
## ๐ Error Object Structure
If the handler catches an error, it forwards:
```ts
{
message: "Something went wrong",
statusCode: 500
}
```
You can access more details if needed:
```ts
error.code
error.stack
error.reason
```
## ๐งช Testing It Out
You can test it with this setup:
```ts
app.use((err, req, res, next) => {
res.status(err.statusCode || 500).json({
error: err.message,
stack: process.env.NODE_ENV === "development" ? err.stack : undefined
});
});
```
## โณ Suggested Folder Structure
```
๐ฆ src/
โโโ asyncHandler.ts
โโโ utils/
โ โโโ mongoErrorHandler.ts
โโโ responses/
โ โโโ ErrorResponse.ts
โ โโโ SuccessResponse.ts
โโโ types/
โ โโโ sharedTypes.ts
```
## ๐ Keywords
```
express, middleware, async handler, async middleware, typescript, error handler, mongoose, transaction, mongodb, nested error handler, api wrapper, clean error handling, success response, error response
```
## ๐ง Future Ideas
- ๐ Localization support for user-friendly error messages.
- ๐ง Limit recursion depth for nested handlers.
- ๐งช Built-in test utils (mocking sessions, errors, etc).
## ๐งโ๐ Author
Made with โค๏ธ by [iBoon Technologies].
Ready to handle errors like a pro?
Use `tranxpress` and say goodbye to callback hell forever. ๐