5 種高級 NodeJS 技術

作爲開發人員,我們都致力於打造高效、健壯且易於理解、修改和擴展的代碼庫。通過採用最佳實踐和探索先進技術,我們可以釋放 NodeJS 的真正潛力並顯着提高應用程序的質量。在這篇文章中,我們將重點介紹 NodeJS 的五種高級技術。所以,繫好安全帶,我們要開車了,準備好探索它們吧。

1. 添加中間件

不要將中間件添加到每個路由,而是使用 use 方法將其添加到路由列表的頂部。這樣,中間件下面定義的任何路由都會在到達各自的路由處理程序之前自動通過中間件。

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);

這種方法有助於保持代碼的組織性,並避免爲每個路由單獨重複中間件。

2. 使用全局錯誤處理

我們可以使用 NodeJS 全局錯誤處理功能,而不是在每個控制器上構建錯誤響應。首先,創建一個派生自內置 Error 類的自定義 AppError 類。此自定義類允許您使用 statusCode 和 status 等附加屬性來自定義錯誤對象。

// 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);
  }
};

創建自定義錯誤類後,請在根路由器文件中添加全局錯誤處理程序中間件。該中間件函數採用四個參數(err、req、res、next)並處理整個應用程序中的錯誤。 

在全局錯誤處理程序中,您可以根據錯誤對象的 statusCode、status 和 message 屬性來格式化錯誤響應。 

您可以自定義此響應格式以滿足您的需求。此外,還包括用於開發環境的堆棧屬性。

// 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)) 拋出錯誤。下一個函數會自動將錯誤傳遞給全局錯誤處理程序中間件。

// 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
  }
});

總體而言,這種方法通過將錯誤處理集中在一個位置來簡化錯誤處理,從而更輕鬆地在應用程序中維護和自定義錯誤響應。

3. 使用自定義 Try-Catch 函數

我們可以使用實現相同目的的自定義函數,而不是使用 try-catch 塊手動包裝每個控制器函數。

// ❌ 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 函數接受函數 (fn) 作爲輸入,並返回一個用 try-catch 塊包裝原始函數的新函數。 

如果在包裝函數內發生錯誤,則使用 catch 方法捕獲錯誤,並將錯誤傳遞到下一個函數以由全局錯誤處理程序處理。

// ✅ 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 包裝控制器函數,您可以確保自動捕獲這些函數中引發的任何錯誤並將其傳遞給全局錯誤處理程序,從而無需單獨添加 try-catch 塊。

這種方法有助於以更清晰、更簡潔的方式集中錯誤處理,使代碼更易於維護並減少重複的錯誤處理代碼。

4. 將主文件分成兩部分。

使用 Express 開發 NodeJS 應用程序時,通常有一個包含所有業務邏輯、路由定義和服務器設置的主文件。 

然而,隨着應用程序的增長,管理和維護處理所有事情的單個文件可能會變得困難。

解決此問題並保持代碼庫更乾淨、更有條理的一種推薦技術是將主文件分爲兩部分:一個用於路由,另一個用於服務器設置或配置。 

這是一個例子:

// 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. 將路由與控制器分開

爲了實現更有組織性和模塊化的代碼庫,我建議將路由與控制器分開。這種做法有助於保持清晰的關注點分離,並提高代碼的可讀性和可維護性。 

這是一個演示路由和控制器分離的示例。

// ❌ 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);

結論

在本文中,我們討論了編寫乾淨且易於維護的 NodeJS 代碼的不同高級技術。有許多最佳實踐可以顯着提高應用程序代碼的質量。 

最後,希望這篇內容對你有用,感謝你的閱讀。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/yhcZoiqwdDddHrIfLR8e4Q