微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将无服务器 yml 文件中的值传递给 js 文件?

如何解决如何将无服务器 yml 文件中的值传递给 js 文件?

serverless.yml file    
provider:
      name: aws
      runtime: nodejs12.x
      memorySize: 512
      stage: ${opt:stage,'test'}
      timeout: 30
    ##
    ##...
    custom:
      getValue: ${file(key.js):randomVal} //pass the string from here


key.js file
module.exports.randomVal = async (context) => {
    #code //get the string here
    console.log(context.providers);
};

在上面的代码中,我从无服务器 yml 文件调用 randomVal() 函数,我想将一个字符串从 yml 文件传递​​给该函数。 有什么办法可以实现吗?

解决方法

我查看了无服务器文档,似乎没有官方方法可以做到这一点。

但是,作为一种解决方法,您可以使用类似 https://www.npmjs.com/package/yaml

的 npm 包解析 key.js 文件中的 serverless.yml 文件

然后做这样的事情:

custom:
  getValue:
    fn: ${file(key.js):randomVal}
    params: 
      someVar: foo
      someOtherVar: bar

当您在 key.js 中解析 serverless.yml 时,您可以使用普通的 not 符号来获取参数:

const YAML = require('yaml')
const fs = require('fs')

const file = fs.readFileSync('./serverless.yml','utf8')
const parsedYaml = YAML.parse(file)

module.exports.randomVal = () => {
    let myVar = parsedYaml.custom.getValue.params.someVar
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。