Last active
January 16, 2022 17:28
-
-
Save paulgalow/4e076577dd5f22cbdf7e16a71ad48255 to your computer and use it in GitHub Desktop.
Post-processing script for 'serverless-manifest-plugin'. Parses manifest output and populates .env file with deployed AWS resource values. Based on: https://github.com/theburningmonk/appsyncmasterclass-backend/blob/873a6bf144e44725c389b198abec5245559fe9bf/processManifest.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dotenv = require("dotenv"); | |
const fs = require("fs").promises; | |
const path = require("path"); | |
module.exports = async function processManifest(manifestData) { | |
const stageName = Object.keys(manifestData)[0]; | |
const { outputs } = manifestData[stageName]; | |
const envArray = outputs | |
.map((obj) => Object.values(obj)) | |
.map((arr) => [camelToUpperSnakeCase(arr[0]), arr[1]]); | |
const envObject = Object.fromEntries(envArray); | |
const dotEnvFile = path.resolve(".env"); | |
await updateDotEnv(dotEnvFile, envObject); | |
}; | |
/* Utils, typically this would be a package includes from NPM */ | |
async function updateDotEnv(filePath, env) { | |
// Merge with existing values | |
try { | |
const existing = dotenv.parse(await fs.readFile(filePath, "utf-8")); | |
env = { ...existing, ...env }; | |
} catch (err) { | |
if (err.code !== "ENOENT") { | |
throw err; | |
} | |
} | |
const contents = Object.keys(env) | |
.map((key) => format(key, env[key])) | |
.join("\n"); | |
await fs.writeFile(filePath, contents); | |
return env; | |
} | |
function escapeNewlines(str) { | |
return str.replace(/\n/g, "\\n"); | |
} | |
function format(key, value) { | |
return `${key}=${escapeNewlines(value)}`; | |
} | |
function camelToUpperSnakeCase(str) { | |
return [...str].reduce((previous, current) => | |
current === current.toUpperCase() | |
? (previous += "_" + current) | |
: (previous += current.toUpperCase()) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment