簡體   English   中英

將 Hapi 插件選項設置為 Node.js 中異步函數調用的值

[英]Set Hapi plugin option to value from async function call in Node.js

我有一個在 Node.js 上運行的 Hapi Web 應用程序,它需要一個插件來使用 yar 處理會話。 除了我需要調用異步函數從 Azure Key Vault 獲取 cookie 密碼外,一切正常。 在這種情況下,我看不到調用異步函數的方法。 我的 index.js 的縮減版本如下所示:

async function createServer () {
  const server = hapi.server({
    port: config.port,
    cache: [{
      name: 'session',
      provider: {
        constructor: catbox,
        options: cacheConfig.catboxOptions
      }
    }],
  })

  await server.register(require('./plugins/yar'))

  return server
}

module.exports = createServer

yar.js 文件如下所示:

module.exports = {
  plugin: require('@hapi/yar'),
  options: {
    maxCookieSize: 0,
    storeBlank: true,
    cache: {
      cache: 'session',
      expiresIn: cacheConfig.expiresIn
    },
    cookieOptions: {
      password: (await readSecret('COOKIE-PASSWORD').value),//This line fails
      isSecure: config.cookieOptions.isSecure,
      ttl: cacheConfig.expiresIn
    }    
  }
}

對 readSecret 的調用是導致我出現問題的調用,因為 readSecret 返回一個 Promise。 如何在不更改 index.js 文件的情況下理想地解決此問題?

好吧,我想我已經找到了解決方案,盡管我不確定這是最好的解決方案。 我創建了一個插件來注冊 yar 插件。

這是我現在在 yar.js 文件中的代碼:

module.exports = {
  name: 'yar',
  register: async function (server, options) {

    const cookiePassword = (await readSecret('COOKIE-PASSWORD')).value

    server.register({
      plugin: require('@hapi/yar'),

      options: {
        maxCookieSize: 0,
        storeBlank: true,
        cache: {
          cache: 'session',
          expiresIn: cacheConfig.expiresIn
        },
        cookieOptions: {
          password: cookiePassword,
          isSecure: config.cookieOptions.isSecure,
          ttl: cacheConfig.expiresIn
        }
      }
    })
  },
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM