Skip to content

Instantly share code, notes, and snippets.

@zerefdev
Last active November 8, 2022 18:06
Show Gist options
  • Save zerefdev/f97ff8a9d00b854e60a95e7cf95a0baa to your computer and use it in GitHub Desktop.
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.
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}` : ''
}`
);
}
});
}
}
@zerefdev
Copy link
Author

zerefdev commented Nov 7, 2022

"scripts": {
    "prebuild": "rimraf dist",
}

to

"scripts": {
    "prebuild": "npx ts-node check_env.ts && rimraf dist",
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment