简体   繁体   English

将 Hapi 插件选项设置为 Node.js 中异步函数调用的值

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

I have a Hapi web application running on Node.js that requires a plugin to handle session using yar.我有一个在 Node.js 上运行的 Hapi Web 应用程序,它需要一个插件来使用 yar 处理会话。 This all works OK except that I need to call an async function the get the cookie password from an Azure Key Vault.除了我需要调用异步函数从 Azure Key Vault 获取 cookie 密码外,一切正常。 I can't see a way to call an async function in this scenario.在这种情况下,我看不到调用异步函数的方法。 A cut down version of my index.js looks like this:我的 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

And the yar.js file looks like this: 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
    }    
  }
}

The call to readSecret is the one that is causing me issues as readSecret returns a Promise.对 readSecret 的调用是导致我出现问题的调用,因为 readSecret 返回一个 Promise。 How can I fix this ideally without changing the index.js file?如何在不更改 index.js 文件的情况下理想地解决此问题?

Well I think I've found a solution although I'm not sure it's the best way of doing it.好吧,我想我已经找到了解决方案,尽管我不确定这是最好的解决方案。 I've created a plugin to register the yar plugin.我创建了一个插件来注册 yar 插件。

This is my code that is now in the yar.js file:这是我现在在 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