我最近使用了 nestjs,但我意识到它过于复杂,我的意思是看下面的代码:
@post('/products')
getAllProducts(@Body('title') title, @Body('price') price, @Body('description') description) { }
Run Code Online (Sandbox Code Playgroud)
它使函数参数变得很脏,而且函数上方可能还有更多装饰器,如@Header、@Params 等。在我看来,这会降低可读性。nodejs中的相同代码
const { title: title, price: price, description: description } = req.body
Run Code Online (Sandbox Code Playgroud)
nodejs 更具可读性...
然后我研究了为什么开发人员使用 nestjs,原因是模块化。为什么我们不自己实现这个......
见下文:
在 app.js 中,我刚刚踢了应用程序:
const express = require('express');
const app = express();
// express config
require('./startup/config')(app);
// handling routes
require('./startup/routes')(app);
// db setup
require('./startup/db')(app);
Run Code Online (Sandbox Code Playgroud)
在启动文件夹中,我做了一些基本的工作,比如 mongoose 配置和连接到 db 等。
但是,在启动/路由中,我只是按如下方式踢了模块:
const shopModule = require('../shop/shop.module');
module.exports = app => {
app.use('/', shopModule);
};
Run Code Online (Sandbox Code Playgroud)
在商店模块中,我只是踢了如下路线:
const router = require('express').Router();
const productsRouter = require('./products/index'); …Run Code Online (Sandbox Code Playgroud)