作為開發(fā)人員,我們都致力于打造高效、健壯且易于理解、修改和擴(kuò)展的代碼庫(kù)。通過采用最佳實(shí)踐和探索先進(jìn)技術(shù),我們可以釋放 NodeJS 的真正潛力并顯著提高應(yīng)用程序的質(zhì)量。在這篇文章中,我們將重點(diǎn)介紹 NodeJS 的五種高級(jí)技術(shù)。所以,系好安全帶,我們要開車了,準(zhǔn)備好探索它們吧。
1.添加中間件
不要將中間件添加到每個(gè)路由,而是使用 use 方法將其添加到路由列表的頂部。這樣,中間件下面定義的任何路由都會(huì)在到達(dá)各自的路由處理程序之前自動(dòng)通過中間件。
const route = express.Router();
const {login} = require("../controllers/auth");
route.get('/login', login)
// isAuthenticated is middleware that checks whether
// you are authenticated or not
// // ? Avoid this: middleware on each route
route.get('/products', isAuthenticated, fetchAllProducts);
route.get('/product/:id', isAuthenticated, getProductById)
// ? Instead, do this
// Route without middleware
route.get('/login', login)
// Middleware function: isAuthenticated
// This will be applied to all routes defined after this point
route.use(isAuthenticated);
// Routes that will automatically check the middleware
route.get('/products', fetchAllProducts);
route.get('/product/:id', getProductById);
這種方法有助于保持代碼的組織性,并避免為每個(gè)路由單獨(dú)重復(fù)中間件。
2.使用全局錯(cuò)誤處理
我們可以使用 NodeJS 全局錯(cuò)誤處理功能,而不是在每個(gè)控制器上構(gòu)建錯(cuò)誤響應(yīng)。首先,創(chuàng)建一個(gè)派生自內(nèi)置 Error 類的自定義 AppError 類。此自定義類允許您使用 statusCode 和 status 等附加屬性來自定義錯(cuò)誤對(duì)象
// Custom Error class
module.exports = class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = statusCode < 500 ? "error" : "fail";
Error.captureStackTrace(this, this.constructor);
}
};
創(chuàng)建自定義錯(cuò)誤類后,請(qǐng)?jiān)诟酚善魑募刑砑尤皱e(cuò)誤處理程序中間件。該中間件函數(shù)采用四個(gè)參數(shù)(err、req、res、next)并處理整個(gè)應(yīng)用程序中的錯(cuò)誤。
在全局錯(cuò)誤處理程序中,您可以根據(jù)錯(cuò)誤對(duì)象的 statusCode、status 和 message 屬性來格式化錯(cuò)誤響應(yīng)。
您可以自定義此響應(yīng)格式以滿足您的需求。此外,還包括用于開發(fā)環(huán)境的堆棧屬性。
// Express setup
const express = require('express');
const app = express();
app.use('/', (req, res) => {
res.status(200).json({ message: "it works" });
});
app.use('*', (req, res) => {
res.status(404).json({
message: `Can't find ${req.originalUrl} this route`,
});
});
// ?? add a global error handler after all the routes.
app.use((err, req, res, next) => {
err.status = err.status || "fail";
err.statusCode = err.statusCode || 500;
res.status(err.statusCode).json({
status: err.status,
message: transformMessage(err.message),
stack: process.env.NODE_ENV === "development" ? err.stack : undefined,
});
});
添加后,您可以使用 next(new AppError(message, statusCode)) 拋出錯(cuò)誤。下一個(gè)函數(shù)會(huì)自動(dòng)將錯(cuò)誤傳遞給全局錯(cuò)誤處理程序中間件。
// inside controllers
// route.get('/login', login);
exports.login = async (req, res, next) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email }).select("+password +lastLoginAt");
if (!user || !(await user.correctPassword(password, user.password))) {
// ?? like this
return next(new AppError("Invalid Email / Password / Method", 404));
}
// Custom logic for generating a token
const token = 'generated_token';
res.status(200).json({ token });
} catch(error) {
next(error
}
});
總體而言,這種方法通過將錯(cuò)誤處理集中在一個(gè)位置來簡(jiǎn)化錯(cuò)誤處理,從而更輕松地在應(yīng)用程序中維護(hù)和自定義錯(cuò)誤響應(yīng)。
3.使用自定義Try-Catch函數(shù)
我們可以使用實(shí)現(xiàn)相同目的的自定義函數(shù),而不是使用 try-catch 塊手動(dòng)包裝每個(gè)控制器函數(shù)。
// ? Avoid this
// Using try-catch block each controllers
exports.login = async (req, res, next) => {
try {
// logic here
} catch(error) {
res.status(400).json({ message: 'You error message'}
}
});
tryCatchFn 函數(shù)接受函數(shù) (fn) 作為輸入,并返回一個(gè)用 try-catch 塊包裝原始函數(shù)的新函數(shù)。
如果在包裝函數(shù)內(nèi)發(fā)生錯(cuò)誤,則使用 catch 方法捕獲錯(cuò)誤,并將錯(cuò)誤傳遞到下一個(gè)函數(shù)以由全局錯(cuò)誤處理程序處理。
// ? Instead, do this
const tryCatchFn = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
}
// To use this custom function, you can wrap your controller
// functions with tryCatchFn:
exports.login = tryCatchFn(async (req, res, next) => {
// logic here
});
通過使用 tryCatchFn 包裝控制器函數(shù),您可以確保自動(dòng)捕獲這些函數(shù)中引發(fā)的任何錯(cuò)誤并將其傳遞給全局錯(cuò)誤處理程序,從而無需單獨(dú)添加 try-catch 塊。
這種方法有助于以更清晰、更簡(jiǎn)潔的方式集中錯(cuò)誤處理,使代碼更易于維護(hù)并減少重復(fù)的錯(cuò)誤處理代碼。
4. 將主文件分成兩部分。
使用 Express 開發(fā) NodeJS 應(yīng)用程序時(shí),通常有一個(gè)包含所有業(yè)務(wù)邏輯、路由定義和服務(wù)器設(shè)置的主文件。
然而,隨著應(yīng)用程序的增長(zhǎng),管理和維護(hù)處理所有事情的單個(gè)文件可能會(huì)變得困難。
解決此問題并保持代碼庫(kù)更干凈、更有條理的一種推薦技術(shù)是將主文件分為兩部分:一個(gè)用于路由,另一個(gè)用于服務(wù)器設(shè)置或配置。
這是一個(gè)例子:
// app.js
const express = require('express');
const app = express();
/* Middlewares */
app.get('/', (req, res) => {
res.status(200).json({ message: "it works" });
})
app.use(/* Global Error Handler */);
module.exports = app;
// server.js
const app = require('./app');
const port = process.env.PORT || 5001;
app.listen(port, () => console.log('Server running at', port));
5. 將路由與控制器分開
為了實(shí)現(xiàn)更有組織性和模塊化的代碼庫(kù),我建議將路由與控制器分開。這種做法有助于保持清晰的關(guān)注點(diǎn)分離,并提高代碼的可讀性和可維護(hù)性。
這是一個(gè)演示路由和控制器分離的示例。
// ? Avoid this
const route = express.Router();
route.get('/login', tryCatchFn(req, res, next) => {
// logic here
}))
// ? Do this
const route = express.Router();
const {login} = require("../controllers/auth");
route.get('/login', login);
結(jié)論文章來源:http://www.zghlxwxcb.cn/news/detail-701275.html
在本文中,我們討論了編寫干凈且易于維護(hù)的 NodeJS 代碼的不同高級(jí)技術(shù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-701275.html
到了這里,關(guān)于5 種高級(jí) NodeJS 技術(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!