diff --git a/config/loader.ts b/config/loader.ts new file mode 100644 index 0000000..b416d22 --- /dev/null +++ b/config/loader.ts @@ -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 +export type DkimRecord = { + domainName: string + keySelector: string + privateKey: string +} +export type AccountRecord = Record + +async function readJsonFile< + T extends JsonRecord, +>(path: string, defaultValue: T): Promise { + 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( + `${basePath}/account.json`, + defaultAccounts, +) +export const dkim = await readJsonFile( + `${basePath}/dkim.json`, + defaultDkim, +) diff --git a/src/contact.ts b/src/contact.ts index 905d35c..a124bfa 100644 --- a/src/contact.ts +++ b/src/contact.ts @@ -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( diff --git a/src/transporter.ts b/src/transporter.ts index dc3b56b..2b670d8 100644 --- a/src/transporter.ts +++ b/src/transporter.ts @@ -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