Skip to content

Commit

Permalink
feat: add get-env-value package (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD authored Oct 25, 2024
2 parents 9680a14 + c958a81 commit 98eddf6
Show file tree
Hide file tree
Showing 8 changed files with 908 additions and 0 deletions.
661 changes: 661 additions & 0 deletions packages/env/LICENSE

Large diffs are not rendered by default.

82 changes: 82 additions & 0 deletions packages/env/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# @alwatr/env

A tiny and tree-shakable TypeScript library to get environment variables with type-safe and fallback value for development and production.

## Installation

```bash
npm install @alwatr/env
```

## Usage

```typescript
import {getEnv} from '@alwatr/env';

const env = getEnv({
name: 'MY_ENV_VAR',
defaultValue: 'default-value',
developmentValue: 'development-value',
});

console.log(env); // Output: 'development-value' in development mode, 'default-value' if MY_ENV_VAR is not set in production mode.
```

## API

### `getEnv(option: GetEnvValueOption): string`

Retrieves the value of an environment variable.

**Parameters:**

* `option`: An object with the following properties:
* `name`: The name of the environment variable.
* `defaultValue`: The default value to use if the environment variable is not set.
* `developmentValue`: The value to use in a development environment.

**Returns:**

The value of the environment variable.

**Throws:**

An error if the environment variable is not set and no default value is provided.

## Examples

**Basic usage:**

```typescript
const dbUrl = getEnv({name: 'DATABASE_URL', defaultValue: 'mongodb://localhost:27017'});
```

**Development value:**

```typescript
const apiUrl = getEnv({
name: 'API_URL',
defaultValue: 'https://api.example.com',
developmentValue: 'http://localhost:3000',
});
```

**Required environment variable:**

```typescript
const apiKey = getEnv({name: 'API_KEY'}); // Throws an error if API_KEY is not set
```

## Sponsors

The following companies, organizations, and individuals support Nanolib ongoing maintenance and development. Become a Sponsor to get your logo on our README and website.

[![Exir Studio](https://avatars.githubusercontent.com/u/181194967?s=200&v=4)](https://exirstudio.com)

### Contributing

Contributions are welcome! Please read our [contribution guidelines](https://github.com/Alwatr/.github/blob/next/CONTRIBUTING.md) before submitting a pull request.

### License

This project is licensed under the [AGPL-3.0 License](LICENSE).
81 changes: 81 additions & 0 deletions packages/env/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
{
"name": "@alwatr/env",
"version": "1.0.0-0",
"description": "A tiny and tree-shakable TypeScript library to get environment variables with type-safe and fallback value for development and production.",
"author": "S. Ali Mihandoost <ali.mihandoost@gmail.com>",
"keywords": [
"get-env",
"getEnv",
"get-env-value",
"env",
"ECMAScript",
"typescript",
"javascript",
"browser",
"esm",
"module",
"utility",
"util",
"utils",
"nanolib",
"alwatr"
],
"type": "module",
"main": "./dist/main.cjs",
"module": "./dist/main.mjs",
"types": "./dist/main.d.ts",
"exports": {
".": {
"types": "./dist/main.d.ts",
"import": "./dist/main.mjs",
"require": "./dist/main.cjs"
}
},
"license": "AGPL-3.0-only",
"files": [
"**/*.{js,mjs,cjs,map,d.ts,html,md,LEGAL.txt}",
"LICENSE",
"!demo/**/*"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/Alwatr/nanolib",
"directory": "packages/env"
},
"homepage": "https://github.com/Alwatr/nanolib/tree/next/packages/env#readme",
"bugs": {
"url": "https://github.com/Alwatr/nanolib/issues"
},
"prettier": "@alwatr/prettier-config",
"scripts": {
"b": "yarn run build",
"t": "yarn run test",
"w": "yarn run watch",
"c": "yarn run clean",
"cb": "yarn run clean && yarn run build",
"d": "yarn run build:es && yarn node --enable-source-maps --trace-warnings",
"build": "yarn run build:ts && yarn run build:es",
"build:es": "nano-build --preset=module",
"build:ts": "tsc --build",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --enable-source-maps --experimental-vm-modules\" jest",
"watch": "yarn run watch:ts & yarn run watch:es",
"watch:es": "yarn run build:es --watch",
"watch:ts": "yarn run build:ts --watch --preserveWatchOutput",
"clean": "rm -rfv dist *.tsbuildinfo"
},
"dependencies": {
"@alwatr/package-tracer": "workspace:^",
"@alwatr/platform-info": "workspace:^"
},
"devDependencies": {
"@alwatr/nano-build": "workspace:^",
"@alwatr/prettier-config": "workspace:^",
"@alwatr/tsconfig-base": "workspace:^",
"@alwatr/type-helper": "workspace:^",
"@types/node": "^22.7.9",
"typescript": "^5.6.3"
}
}
45 changes: 45 additions & 0 deletions packages/env/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {packageTracer} from '@alwatr/package-tracer';
import {platformInfo} from '@alwatr/platform-info';

__dev_mode__: packageTracer.add(__package_name__, __package_version__);

/**
* Parameters for retrieving an environment variable value.
*/
export type GetEnvOption = {
/**
* The name of the environment variable.
*/
name: string;

/**
* The default value to use if the environment variable is not set.
* If not provided, the environment variable is required and an error will be thrown if it is not set.
* Except in development mode, where the development value will be used instead if provided.
*/
defaultValue?: string;

/**
* The value to use in a development environment.
* It will be overwrite the default value in development mode and completely ignored in production mode.
*/
developmentValue?: string;
}

export function getEnv(option: GetEnvOption): string {
let value = process.env[option.name];
if (value === '') value = undefined; // empty string is considered as undefined in environment variables

if (platformInfo.development === true) {
value ??= option.developmentValue ?? option.defaultValue;
}
else {
value ??= option.defaultValue;
}

if (value === undefined) {
throw new Error(`Environment variable "${option.name}" is required.`);
}

return value;
}
12 changes: 12 additions & 0 deletions packages/env/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "@alwatr/tsconfig-base/tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"emitDeclarationOnly": true,
"composite": true,
"types": ["node", "@alwatr/nano-build", "@alwatr/type-helper"]
},
"include": ["src/**/*.ts"],
"references": []
}
1 change: 1 addition & 0 deletions packages/nanolib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
"@alwatr/dedupe": "workspace:^",
"@alwatr/deep-clone": "workspace:^",
"@alwatr/delay": "workspace:^",
"@alwatr/env": "workspace:^",
"@alwatr/exit-hook": "workspace:^",
"@alwatr/fetch": "workspace:^",
"@alwatr/flat-string": "workspace:^",
Expand Down
1 change: 1 addition & 0 deletions packages/nanolib/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from '@alwatr/platform-info';
export * from '@alwatr/render-state';
export * from '@alwatr/unicode-digits';
export * from '@alwatr/resolve-url';
export * from '@alwatr/env';
25 changes: 25 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,21 @@ __metadata:
languageName: unknown
linkType: soft

"@alwatr/env@workspace:^, @alwatr/env@workspace:packages/env":
version: 0.0.0-use.local
resolution: "@alwatr/env@workspace:packages/env"
dependencies:
"@alwatr/nano-build": "workspace:^"
"@alwatr/package-tracer": "workspace:^"
"@alwatr/platform-info": "workspace:^"
"@alwatr/prettier-config": "workspace:^"
"@alwatr/tsconfig-base": "workspace:^"
"@alwatr/type-helper": "workspace:^"
"@types/node": "npm:^22.7.9"
typescript: "npm:^5.6.3"
languageName: unknown
linkType: soft

"@alwatr/eslint-config@workspace:^, @alwatr/eslint-config@workspace:packages/eslint-config":
version: 0.0.0-use.local
resolution: "@alwatr/eslint-config@workspace:packages/eslint-config"
Expand Down Expand Up @@ -218,6 +233,7 @@ __metadata:
"@alwatr/dedupe": "workspace:^"
"@alwatr/deep-clone": "workspace:^"
"@alwatr/delay": "workspace:^"
"@alwatr/env": "workspace:^"
"@alwatr/exit-hook": "workspace:^"
"@alwatr/fetch": "workspace:^"
"@alwatr/flat-string": "workspace:^"
Expand Down Expand Up @@ -2232,6 +2248,15 @@ __metadata:
languageName: node
linkType: hard

"@types/node@npm:^22.7.9":
version: 22.7.9
resolution: "@types/node@npm:22.7.9"
dependencies:
undici-types: "npm:~6.19.2"
checksum: 10c0/2d1917702b9d9ede8e4d8151cd8b1af8bc147d543486474ffbe0742e38764ea73105939e6a767addf7a4c39e842e16eae762bff90617d7b7f9ee3fbbb2d23bfa
languageName: node
linkType: hard

"@types/normalize-package-data@npm:^2.4.1, @types/normalize-package-data@npm:^2.4.3":
version: 2.4.4
resolution: "@types/normalize-package-data@npm:2.4.4"
Expand Down

0 comments on commit 98eddf6

Please sign in to comment.