Node.js 多租戶指南

    本指南將引導您在處理敏感醫療資料的多租戶 Node.js 應用程式中實作搜尋功能。

    什麼是多租戶?

    在 Meilisearch 中,您可能會有一個索引包含屬於許多不同租戶的資料。在這種情況下,您的租戶必須只能搜尋他們自己的文件。您可以使用租戶令牌來實作此功能。

    需求

    提示

    偏好自行託管?請閱讀我們的安裝指南

    資料模型

    本指南使用簡單的資料模型來表示醫療預約。Meilisearch 索引中的文件將如下所示

    [
      {
        "id": 1,
        "patient": "John",
        "details": "I think I caught a cold. Can you help me?",
        "status": "pending"
      },
      {
        "id": 2,
        "patient": "Zia",
        "details": "I'm suffering from fever. I need an appointment ASAP.",
        "status": "pending"
      },
      {
        "id": 3,
        "patient": "Kevin",
        "details": "Some confidential information Kevin has shared.",
        "status": "confirmed"
      }
    ]
    

    在本指南中,我們假設文件儲存在 appointments 索引中。

    建立租戶令牌

    第一步是產生一個租戶令牌,該令牌將允許指定的病患僅搜尋他們的預約。若要達成此目的,您必須先建立一個租戶令牌,該令牌會根據病患的 ID 過濾結果。

    建立一個 search.js 檔案,並使用下列程式碼產生租戶令牌

    // search.js
    
    import { Meilisearch } from 'meilisearch'
    
    const apiKey = 'YOUR_SEARCH_API_KEY'
    const apiKeyUid = 'YOUR_SEARCH_API_KEY_UID'
    const indexName = 'appointments'
    
    const client = new Meilisearch({
    	host: 'https://edge.meilisearch.com', // Your Meilisearch host
    	apiKey: apiKey
    })
    
    export function createTenantToken(patientName) {
      const searchRules = {
        [indexName]: {
          'filter': `patient = ${patientName}`
        }
      }
    
      const tenantToken = client.generateTenantToken(
        apiKeyUid,
        searchRules,
        {
          expiresAt: new Date('2030-01-01'), // Choose an expiration date
          apiKey: apiKey,
        }
      )
      return tenantToken
    }
    

    當 Meilisearch 收到包含租戶令牌的搜尋查詢時,它會解碼該令牌並將搜尋規則套用至搜尋請求。在此範例中,結果會依 patient 欄位篩選。這表示病患只能搜尋他們自己的預約。

    使用租戶令牌

    現在您已經有租戶令牌,請使用它來執行搜尋。若要達成此目的,您需要

    提供租戶令牌

    本指南使用 Express.js 來建立伺服器。您可以執行以下命令來安裝 express

    # with NPM
    npm i express
    # with Yarn
    yarn add express
    # with pnpm
    pnpm add express
    

    然後,在 server.js 檔案中加入下列程式碼

    // server.js
    
    import express from 'express'
    import { createTenantToken } from './search.js'
    
    const server = express()
    
    server.get('/token', async (request, response) => {
      const { id: patientId } = request.query
      const token = createTenantToken(patientId)
      return response.json({ token });
    })
    
    server.listen(3000, () => {
      console.log('Server is running on port 3000')
    })
    

    此程式碼會在 https://127.0.0.1:3000/token 建立一個端點,該端點會接受一個 id 查詢參數並傳回一個租戶令牌。

    現在我們有了一個端點,您將使用它來在您的前端應用程式中擷取租戶令牌。本指南使用 InstantSearch.js 來建立搜尋介面。您將使用 CDN 連結來在您的 HTML 檔案中包含 InstantSearch.js 和 Meilisearch InstantSearch.js 連接器。

    建立 client.html 檔案並插入以下程式碼

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css" />
      </head>
      <body>
        <div class="wrapper">
          <div id="searchbox" focus></div>
          <div id="hits"></div>
        </div>
      </body>
      <script src="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4"></script>
      <script>
        document.addEventListener('DOMContentLoaded', async () => {
          const patientId = 1 // Replace with the patient's ID
          const response = await fetch(`https://127.0.0.1:3000/token?id=${patientId}`)
          const { token } = await response.json()
    
          const search = instantsearch({
            indexName: 'appointments',
            searchClient: instantMeiliSearch(
              'https://edge.meilisearch.com',
              token
            ).searchClient
          })
    
          search.addWidgets([
            instantsearch.widgets.searchBox({
              container: "#searchbox"
            }),
            instantsearch.widgets.hits({
              container: "#hits",
              templates: {
              item: `
                <div>
                  <div class="hit-name">
                        {{#helpers.highlight}}{ "attribute": "patient" }{{/helpers.highlight}}
                  </div>
                  <div class="hit-description">
                    {{#helpers.highlight}}{ "attribute": "details" }{{/helpers.highlight}}
                  </div>
                </div>
              `
              }
            })
          ])
    
          search.start()
        })
      </script>
    </html>
    

    太棒了!您已成功在 Node.js 應用程式中實作安全的、多租戶的搜尋功能。使用者將只能搜尋屬於他們的文件。

    結論

    在本指南中,您了解如何在 Node.js 應用程式中實作安全的、多租戶搜尋功能。接著,您建立了一個端點,為每個使用者產生租戶權杖。您還使用 InstantSearch 建置了搜尋介面,以便使用租戶權杖進行搜尋。

    本指南中的所有程式碼都取自我們的多租戶範例應用程式。程式碼可在 GitHub上取得。