🌳
pt0/serverF/envConfF.mts
1import fs from 'fs'
2import * as _ from 'lodash-es'
3import { ptDir } from './ptDirF.mts'
5import { pathDownJoin } from './pathF.mts'
13export type envConfType = Record<string, any> & {
14 allNodePorts?: Record<string, NodePortsCfg>
15 nodePorts?: Record<string, NodePortsCfg>
16 secretsMapping?: Record<string, string>
17 dbSecrets?: Record<string, string>
18 readonly __brand: unique symbol
21export const tsEnvConf = <T extends Record<string, any>>(s: T): T & envConfType => s as T & envConfType
23export const envConfCtx = genContext<envConfType>('envConf')
25export const readSecretPath = (secretPath: string): string | undefined => {
26 if (!fs.existsSync(secretPath)) return
28 const isDir = fs.lstatSync(secretPath).isDirectory()
29 throwIf(() => isDir, {secretPath})
31 return _.trim(fs.readFileSync(secretPath, 'utf8'))
34export const envConfPath = pathDownJoin(ptDir, 'data/envConf.json')
36export let cachedEnvConf: envConfType | undefined
37let cachedEnvConfS: string | undefined
39export const setEnvConf = (envConf: envConfType): boolean => {
40 const ctxStore = envConfCtx.getStore()
41 if (ctxStore) {
42 Object.assign(ctxStore, envConf)
43 return false
44 }
45 cachedEnvConf = envConf
46 cachedEnvConfS = JSON.stringify(envConf)
47 return true
50export const getEnvConfOpt = (): envConfType | undefined => {
51 const ctxConf = envConfCtx.getStore()
52 if (ctxConf) return ctxConf
53 const envConfS = isDevPc ? process.env.ENVCONFS : (process.env.ENVCONFS || readSecretPath(envConfPath))
54 if (envConfS !== cachedEnvConfS) {
55 cachedEnvConfS = envConfS
56 if (envConfS) cachedEnvConf = undefined
57 }
58 if (cachedEnvConf) return cachedEnvConf as envConfType
59 const parsedJson = json1ParseCatch(envConfS as string)
60 if (!parsedJson) return
61 cachedEnvConf = parsedJson as envConfType
62 return cachedEnvConf
65export const getEnvConf = (): envConfType => {
66 const envConf = getEnvConfOpt()
67 assertDefined(envConf)
68 return envConf
71export const getEnvConfItem = (key: string): unknown => getEnvConf()[key]