feat: load config files from local fs and fallback if needed

This commit is contained in:
Julien Oculi 2025-02-20 15:38:00 +01:00
parent 486a3da213
commit d33dd4539a
3 changed files with 52 additions and 4 deletions

49
config/loader.ts Normal file
View file

@ -0,0 +1,49 @@
import type { JsonValue } from '@std/json'
import defaultAccounts from './account.json' with { type: 'json' }
import defaultDkim from './dkim.json' with { type: 'json' }
function checkFsErrors(error: Error) {
if (error instanceof Deno.errors.NotFound) {
//use default config file
return
}
if (error instanceof Deno.errors.PermissionDenied) {
throw new Error(
'unable to load config file due to read access permissions issues',
{
cause: error,
},
)
}
throw error
}
type JsonRecord = Record<string, JsonValue>
export type DkimRecord = {
domainName: string
keySelector: string
privateKey: string
}
export type AccountRecord = Record<string, {
name: string
address: string
}>
async function readJsonFile<
T extends JsonRecord,
>(path: string, defaultValue: T): Promise<T> {
const file = await Deno.readTextFile(path).catch(checkFsErrors)
const json = JSON.parse(file ?? '{}')
return { ...defaultValue, ...json }
}
const basePath = '/ect/cohabit/mailer'
export const accounts = await readJsonFile<AccountRecord>(
`${basePath}/account.json`,
defaultAccounts,
)
export const dkim = await readJsonFile<DkimRecord>(
`${basePath}/dkim.json`,
defaultDkim,
)

View file

@ -1,5 +1,4 @@
import accounts from '../config/account.json' with { type: 'json' }
import dkim from '../config/dkim.json' with { type: 'json' }
import { accounts, dkim } from '../config/loader.ts'
export type AddressString = `${string}@${string}.${string}`
@ -22,7 +21,7 @@ export class Contact {
throw new Error('unknown short name contact')
}
const { name, address } = accounts[shortName as keyof typeof accounts]
const { name, address } = accounts[shortName]
if (typeof name !== 'string') {
throw new SyntaxError(

View file

@ -1,6 +1,6 @@
// @deno-types="npm:@types/nodemailer@^6.4.15"
import nodemailer from 'nodemailer'
import dkim from '../config/dkim.json' with { type: 'json' }
import { dkim } from '../config/loader.ts'
export async function transporter() {
const dkimPath = dkim.privateKey