UNPKG

@rytass/secret-adapter-vault-nestjs

Version:

Rytass Sceret Vault nestjs adapter

76 lines (73 loc) 2.71 kB
import { Injectable, Inject } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { VaultSecret, VaultSecretState } from '@rytass/secret-adapter-vault'; import { VAULT_PATH_TOKEN } from './constants.js'; function _ts_decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function _ts_metadata(k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); } function _ts_param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } class VaultService { config; manager; onReadyCallbacks; fallbackToEnvFile; constructor(config, path){ this.config = config; this.onReadyCallbacks = []; this.fallbackToEnvFile = false; const host = config.get('VAULT_HOST'); const user = config.get('VAULT_ACCOUNT'); const pass = config.get('VAULT_PASSWORD'); if (!host) { this.fallbackToEnvFile = true; return; } this.manager = new VaultSecret(path, { host, auth: { account: user, password: pass }, onError: (err)=>{ this.fallbackToEnvFile = true; this.onReadyCallbacks.forEach((done)=>done(config)); }, onReady: ()=>{ this.onReadyCallbacks.forEach((done)=>done()); } }); } async get(key) { if (this.fallbackToEnvFile) { return Promise.resolve(this.config.get(key) || ''); } if (this.manager.state === VaultSecretState.READY) { return this.manager.get(key); } return new Promise((resolve)=>{ this.onReadyCallbacks.push((dataSource = this.manager)=>{ resolve(dataSource.get(key)); }); }); } } VaultService = _ts_decorate([ Injectable(), _ts_param(1, Inject(VAULT_PATH_TOKEN)), _ts_metadata("design:type", Function), _ts_metadata("design:paramtypes", [ typeof ConfigService === "undefined" ? Object : ConfigService, String ]) ], VaultService); export { VaultService };