如何将无服务器 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
};