express-asyncmw
Async handler for express.js
How to Use
- Import the library in your code
JavaScript
const { asyncMw, errorAsyncMw } = require('express-asyncmw');
TypeScript
import { asyncMw, errorAsyncMw } from 'express-asyncmw';
- Use the imported functions
JavaScript
const { asyncMw, errorAsyncMw } = require('express-asyncmw');
const getUserMw = asyncMw(async (req, res, next) => {
});
const getUserMw = errorAsyncMw(async (err, req, res, next) => {
});
TypeScript
import { asyncMw, errorAsyncMw } from 'express-asyncmw';
const getUserMw = asyncMw(async (req, res, next) => {
});
const getUserMw = errorAsyncMw(async (err, req, res, next) => {
});
Using Additional Types
In case if you want to some sort of intellisense things for you types. Consider setting it up this way.
- Import all the necessary things
import { asyncMw, AsyncParam } from 'express-asyncmw';
export const getUserMw = asyncMw(async (req, res, next) => {
});
- Create the new additional types
type User = {
id: number;
username: string;
email: string;
createdAt: string;
};
- Implement new types to
asyncMw
import { asyncMw, AsyncParam } from 'express-asyncmw';
type User = {
id: number;
username: string;
email: string;
createdAt: string;
};
export const getUserMw = asyncMw<{ extends: { user: User } }>(async (req, res, next) => {
req.user.id = 'id';
});
- Adding lot of types to
request and response object
import { asyncMw } from 'express-asyncmw';
type User = {
id: number;
username: string;
email: string;
createdAt: string;
};
type GetUserMwParam = {
params: {
id: string;
};
resBody: {
status: number;
};
reqBody: {
username: string;
};
reqQuery: {
createdAt: string;
};
extends: {
user: User;
};
};
asyncMw<GetUserMwParam>((req, res, next) => {
if (!req.params.id) return;
req.user.id = 'id';
req.user.username = req.body.username;
res.json({
status: '200',
});
});