Node.js中从异步函数取值设置Hapi插件yar选项的方案
解决Hapi Yar插件异步获取Azure Key Vault密码的问题
原代码报错原因:await 只能在 async 函数内部使用,你直接在对象字面量的属性值中使用 await,脱离了异步函数上下文,导致语法错误。
以下是无需修改 index.js 的解决方案:
修改 yar.js,将原本直接导出的插件配置对象,替换为自执行异步函数(返回Promise),在函数内部先获取密钥,再返回完整插件配置:
// 确保已正确导入 readSecret、config、cacheConfig module.exports = (async () => { // 异步获取Azure Key Vault中的cookie密码 const cookiePassword = await readSecret('COOKIE-PASSWORD').value; return { 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 } } }; })();
原理说明:
Hapi 的 server.register() 方法支持接收一个 Promise,该 Promise 最终解析为合法的插件配置对象。当 index.js 执行 await server.register(require('./plugins/yar')) 时,require('./plugins/yar') 返回的是已启动执行的 Promise,await 会等待这个 Promise 完成,拿到解析后的插件配置再完成注册流程,完全兼容原有代码逻辑。
内容的提问来源于stack exchange,提问作者fosbie
相关产品推荐
相关产品推荐

