首頁  >  文章  >  web前端  >  Nuxt 中的請求上下文

Nuxt 中的請求上下文

Patricia Arquette
Patricia Arquette原創
2024-10-26 06:39:02363瀏覽

Request context in Nuxt

介紹

Nuxt 最近引入了一項實驗性功能:使用 NodeJS AsyncLocalStorage 的非同步上下文支援。
此增強功能有望簡化開發人員跨嵌套非同步函數管理上下文的方式,但還有更多!

需要注意的是,「實驗性」標籤是由於跨平台支援有限;但是,在使用NodeJS 時它很穩定,使其成為在該環境中工作的開發人員的可靠選擇。

https://nuxt.com/docs/guide/going-further/experimental-features#asynccontext

NodeJS 中的 AsyncLocalStorage 允許您跨非同步操作一致地儲存和存取資料。它維護上下文,使管理用戶會話或請求特定資訊等資料變得更加容易。

AsyncContext 解決什麼問題?

  • 跨非同步操作的上下文一致性AsyncContext確保上下文資料在所有非同步呼叫中保持可訪問,而無需手動將其傳遞到函數層。

  • 減少樣板程式碼:透過消除重複的上下文傳遞邏輯來簡化程式碼庫。

維護一致的請求上下文一直是 NodeJS 應用程式中的一個挑戰,甚至在 Nuxt 之前也是如此。

有問題的

一個用例是實施日誌系統來追蹤客戶通過我們網站的路徑。為了實現這一目標,我們需要在每個日誌條目中包含一個相關 ID,以確保我們能夠一致地追蹤每個客戶的旅程。

這個問題是,當您有更多具有多層的應用程式邏輯時,您必須將上下文傳遞到這些層。

讓我們來看一個例子:

nuxt-demo-async-context/
├── public/
│   └── favicon.ico
├── server/
│   ├── api/
│   │   ├── index.ts
│   │   └── users.ts
│   ├── middleware/
│   │   └── correlationId.middleware.ts
│   ├── repository/
│   │   └── user.repository.ts
│   ├── service/
│   │   └── user.service.ts
│   └── utils/
│       └── logger.ts
├── .gitignore
├── README.md
├── app.vue
├── nuxt.config.ts
├── package-lock.json
├── package.json
├── tsconfig.json
└── yarn.lock

文件結構和代碼草稿

1. [id].ts

export default defineEventHandler((event) => {
  const id = event.context.params.id;
  const { correlationId } = event.context;
  try {
    const user = userService.getUserById(id, correlationId);
    return {
      user,
      message: `User with ID ${id} retrieved successfully`
    };
  } catch (error) {
    return {
      statusCode: 404,
      message: `User with ID ${id} not found`
    };
  }
});

1. userRepository.ts

// This would typically interact with a database
const users = new Map<string, { id: string; name: string; email: string }>();

export default {
  findById(id: string) {
    return users.get(id) || null;
  },

  save(user: { id: string; name: string; email: string }) {
    users.set(user.id, user);
    return user;
  }
};

如您所見,問題在於我們在每個層上傳遞了作為請求上下文的correlationId 變量,這意味著每個函數都對correlationId 變數有依賴性。

現在想像一下我們是否必須對每個應用程式邏輯執行此操作。

請不要在全域變數中設定此類邏輯,NodeJS 將在每個使用者的每個請求之間共用此上下文。

解決方案

AsyncContext可以解決這個問題!

一旦您啟動 Nuxt 中的實驗性功能 asyncContext。

您現在可以從任何地方存取該活動。

我們可以建立一個中間件,將該correlationId 傳遞給事件,以便在應用程式中的任何位置可用:

伺服器/中間件/correlationId.ts

nuxt-demo-async-context/
├── public/
│   └── favicon.ico
├── server/
│   ├── api/
│   │   ├── index.ts
│   │   └── users.ts
│   ├── middleware/
│   │   └── correlationId.middleware.ts
│   ├── repository/
│   │   └── user.repository.ts
│   ├── service/
│   │   └── user.service.ts
│   └── utils/
│       └── logger.ts
├── .gitignore
├── README.md
├── app.vue
├── nuxt.config.ts
├── package-lock.json
├── package.json
├── tsconfig.json
└── yarn.lock

現在我們可以做類似的事情:

export default defineEventHandler((event) => {
  const id = event.context.params.id;
  const { correlationId } = event.context;
  try {
    const user = userService.getUserById(id, correlationId);
    return {
      user,
      message: `User with ID ${id} retrieved successfully`
    };
  } catch (error) {
    return {
      statusCode: 404,
      message: `User with ID ${id} not found`
    };
  }
});

不再需要將請求或參數傳遞給我們的記錄器。

我們可以應用此技術來取得使用者上下文,這是一個常見的用例。

結論

AsyncContext 簡化了 Nuxt 應用程式中的上下文管理,減少了樣板程式碼並確保非同步操作之間的一致性。

我們可以進一步透過為請求上下文或用戶服務等服務實現依賴注入。

這種方法減少了耦合並最大限度地減少了層之間的依賴關係,使程式碼庫更加模組化,更易於維護和測試。

進一步閱讀

PoC 可在此處 https://github.com/marc-arnoult/nuxt-demo-ync-context

有關如何實現 AsyncContext 以及探索 Nuxt 中其他實驗性功能的更多詳細信息,請查看官方文件。
https://nodejs.org/api/async_context.html

以上是Nuxt 中的請求上下文的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn