我使用TypeScript使用Node和Express创建了一个非常简单的REST API,异步路由用包装器包装起来以捕获所有错误,并在中间件中进行处理。
我已经使用js的一个非常基本的示例尝试了相同的包装器和中间件,并且效果很好,我不知道它会逃避我,我希望有人能帮助我。
我将包含要测试的路由的类和服务器的类留在这里:
const asyncWrapper = (fn: any) => (req: Request, res: Response, next: any): Promise<any> => Promise.resolve(fn(req, res, next)).catch(next);
const errorHandlingMiddlware = (error: any, req: Request, res: Response, next: NextFunction) => {
res.status(450);
res.json({
ok: false,
error: error.message
});
next();
}
class ClientRoutes {
public router: Router;
constructor(){
this.router = Router();
this.routes();
}
//get a client for our db, receives an id on url.
async getClient(req: Request, res: Response, next: NextFunction): Promise<void>{
const id: String = req.params.id;
const client: Client|null = await ClientModel.findById(id);
res.json({
ok: true,
client
});
}
routes(){
this.router.get('/:id',asyncWrapper(this.getClient));
}}
const clientRoutes: ClientRoutes = new ClientRoutes();
export default clientRoutes.router;
class Server {
public app: express.Application;
constructor(){
this.app = express();
this.config();
this.routes();
}
config(){
const MONGODB_URI: string = 'mongodb://localhost/paint_admin_db';
mongoose.connect(process.env.MONGODB_URI || MONGODB_URI,{
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
//Settings
this.app.set('port',process.env.PORT || 3000);
//Middlewares
this.app.use(express.json());
this.app.use(express.urlencoded({extended: false}));
this.app.use(helmet());
this.app.use(compression());
this.app.use(cors());
this.app.use(myLogger);
this.app.use(errorHandlingMiddlware);
}
routes(){
this.app.use('/api/clients',ClientRoutes);
this.app.use('/api/tasks',TaskRoutes)
}
start(){
const port = this.app.get('port');
this.app.listen(port,() => console.log(`Server on port: ${port}`));
}
}
使用不存在的ID调用getClient路由会引发典型的猫鼬错误。