mybase 1.0.46 → 1.0.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/mybase.js +32 -1
  2. package/package.json +1 -1
package/mybase.js CHANGED
@@ -161,22 +161,53 @@ async function getMysql(mysqlClass,config,keep_pinging=true) {
161
161
  })
162
162
  }
163
163
 
164
- function vaultRead(vault, key) {
164
+ function fileCacheIsValid(cacheFile, cache_in_minutes = 60) {
165
+ if (fs.existsSync(cacheFile)) {
166
+ const stat = fs.statSync(cacheFile)
167
+ const mtime = new Date(stat.mtime).getTime()
168
+ if (Date.now() - mtime < cache_in_minutes * 60 * 1000) {
169
+ // cache is still valid
170
+ return true
171
+ }
172
+ }
173
+ return false
174
+ }
175
+
176
+ function vaultRead(vault, key, cache_in_minutes = 10) {
177
+ // v2 - supports caching
165
178
  return new Promise((resolve, reject) => {
179
+ let cache_file = path.join(vault_cache_folder,hash_sha512(`${vault.endpoint}/${key}`))
180
+ if (cache_in_minutes>0 && fileCacheIsValid(cache_file,cache_in_minutes))
181
+ return resolve(JSON.parse(fs.readFileSync(cache_file)))
182
+
166
183
  vault.read(key).then((r) => {
167
184
  if (r.data) {
168
185
  debug(`vault ${key} - success`)
186
+ if (cache_in_minutes>0)
187
+ try { fs.writeFileSync(cache_file, JSON.stringify(r.data)); fs.chmodSync(cache_file,0o600); } catch(_) {}
169
188
  return resolve(r.data);
170
189
  }
171
190
  debug(`vault ${key} - failed`)
172
191
  reject(r);
173
192
  }).catch(e => {
193
+ console.log(e)
174
194
  debug(`exception inside vaultRead`, e)
195
+ // we will still return latest information from cache
196
+ try {
197
+ console.log(chalk.bgRed(`returning vault@${key} from cache due to error`))
198
+ if (fs.existsSync(cache_file))
199
+ return resolve(JSON.parse(fs.readFileSync(cache_file)))
200
+ }catch(e2) {
201
+ // content of the file is invalid
202
+ console.log(e2)
203
+ }
204
+
175
205
  reject(e);
176
206
  })
177
207
  })
178
208
  }
179
209
 
210
+
180
211
  function vaultFill(vault, obj, ignoreError = false, keepCache=true) {
181
212
  // v2.1
182
213
  // fills all strings with ^vault@/secret/... with proper vault values
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mybase",
3
- "version": "1.0.46",
3
+ "version": "1.0.48",
4
4
  "description": "",
5
5
  "main": "mybase.js",
6
6
  "scripts": {