Files
P42_wssGateway/configHelper.js
T
2025-10-06 17:38:43 +00:00

50 lines
1.6 KiB
JavaScript

import Ajv from 'ajv'
import confSchema from './configSchema.json' with { type: 'json' }
import { pathToFileURL } from 'url'
export class configHelper {
constructor(options){
this.config = {}
this.localfile = options.localfile
this.fetchConfig = this.fetchConfigFile
this.refreshAccessRights = this.refreshAccessRightsFile
const ajv = new Ajv({
allowUnionTypes: true
})
this.configValidator = ajv.compile(confSchema)
}
isValidConfig(conf){
if(this.configValidator(conf)) return(true)
console.error('Invalid configuration: ', this.configValidator.errors)
return(false)
}
async fetchConfigFile(){
let curConfig = this.config
const url = pathToFileURL(this.localfile).href
this.config = await import(url, {
with: { type: 'json' }
}).then(m => m.default)
if(this.isValidConfig(this.config)) return(this.config)
console.error(this.isValidConfig.errors)
//revert if invalid conf
this.config = curConfig
}
async refreshAccessRightsFile(){
let tmp
try { tmp = import(`${this.localfile}?update=${Date.now()}`, { assert: { type: 'json' } }) }
catch(err) {
console.error('Error Reloading config !! (bad json?) => Keeping current accessRights !')
return
}
if(!tmp.accessRights) {
console.error('Error Reloading config !! (no accessRights !) => Keeping current accessRights !')
return
}
this.config.accessRights = tmp.accessRights
}
}