Last active
November 8, 2022 18:06
-
-
Save zerefdev/f97ff8a9d00b854e60a95e7cf95a0baa to your computer and use it in GitHub Desktop.
Nest.js: check if all used environment variables are defined in .env before building.
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
import { createReadStream } from 'node:fs'; | |
import { readdir } from 'node:fs/promises'; | |
import { resolve } from 'node:path'; | |
let envFileContent = ''; | |
createReadStream('.env') | |
.on('data', (chunk) => { | |
envFileContent += chunk.toString(); | |
}) | |
.on('end', () => { | |
checkEnv(envFileContent.split('\n').filter((l) => l !== '')); | |
}); | |
async function* getFiles(dir: string): AsyncGenerator<string> { | |
const dirents = await readdir(dir, { withFileTypes: true }); | |
for (const dirent of dirents) { | |
const file = resolve(dir, dirent.name); | |
if (dirent.isDirectory()) yield* getFiles(file); | |
else yield file; | |
} | |
} | |
async function checkEnv(envArr: string[]) { | |
for await (const file of getFiles('./src')) { | |
let content = ''; | |
createReadStream(file) | |
.on('data', (chunk) => { | |
content += chunk.toString(); | |
}) | |
.on('end', () => { | |
const arr = content.split('\n'); | |
for (const line of arr) { | |
const match = line.match( | |
/configService\.get.*\((\S*(?:'|"))(?:\)|,\s)?((\S*(?:'|")))/ | |
); | |
if (!match) continue; | |
const envKey = match[1].replaceAll(/'|"/g, ''); | |
const defaultValue = match[3]?.replaceAll(/'|"/g, ''); | |
const foundEnv = envArr.find((env) => env.startsWith(envKey)); | |
if (!foundEnv || envKey + '=' === foundEnv) | |
throw new Error( | |
`A used process.env.${envKey} is not defined in the '.env' file. ${ | |
defaultValue ? `defaultValue: ${defaultValue}` : '' | |
}` | |
); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to