|
| 1 | +/* |
| 2 | + * @adonisjs/env |
| 3 | + * |
| 4 | + * (c) AdonisJS |
| 5 | + * |
| 6 | + * For the full copyright and license information, please view the LICENSE |
| 7 | + * file that was distributed with this source code. |
| 8 | + */ |
| 9 | + |
| 10 | +import { Secret } from '@poppinss/utils' |
| 11 | +import { type Prettify } from '@poppinss/utils/types' |
| 12 | +import { schema as envSchema } from '@poppinss/validator-lite' |
| 13 | +import { type SchemaFnOptions } from '@poppinss/validator-lite/types' |
| 14 | + |
| 15 | +function secret(options?: SchemaFnOptions) { |
| 16 | + return function validate(key: string, value?: string): Secret<string> { |
| 17 | + if (!value) { |
| 18 | + throw new Error(options?.message ?? `Missing environment variable "${key}"`) |
| 19 | + } |
| 20 | + return new Secret(value) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Same as the Secret rule, but allows non-existing values too |
| 26 | + */ |
| 27 | +secret.optional = function optionalString() { |
| 28 | + return function validate(_: string, value?: string): Secret<string> | undefined { |
| 29 | + if (!value) { |
| 30 | + return undefined |
| 31 | + } |
| 32 | + return new Secret(value) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Same as the optional rule, but allows a condition to decide when to |
| 38 | + * validate the value |
| 39 | + */ |
| 40 | +secret.optionalWhen = function optionalWhenString( |
| 41 | + condition: boolean | ((key: string, value?: string) => boolean), |
| 42 | + options?: SchemaFnOptions |
| 43 | +) { |
| 44 | + return function validate(key: string, value?: string): Secret<string> | undefined { |
| 45 | + if (typeof condition === 'function' ? condition(key, value) : condition) { |
| 46 | + return secret.optional()(key, value) |
| 47 | + } |
| 48 | + |
| 49 | + return secret(options)(key, value) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +export const schema: Prettify< |
| 54 | + typeof envSchema & { |
| 55 | + secret: typeof secret |
| 56 | + } |
| 57 | +> = { |
| 58 | + ...envSchema, |
| 59 | + secret, |
| 60 | +} |
0 commit comments