mailer/src/contact.ts

75 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-03-28 22:32:46 +01:00
import custom from '../config/account.json' with { type: 'json' }
export class Contact {
#name: string
#address: `${string}@${string}.${string}`
constructor(
{ name, address }: {
name: string
address: `${string}@${string}.${string}`
},
) {
this.#name = name
this.#address = address
}
static expand(shortName: string): Contact {
if (!(shortName in custom)) {
throw new Error('unknown short name contact')
}
const { name, address } = custom[shortName as keyof typeof custom]
2024-04-04 17:11:32 +02:00
if (typeof name !== 'string') {
2024-03-28 22:32:46 +01:00
throw new SyntaxError(
`missing key "name" in contact short name config for "${shortName}"`,
)
}
2024-04-04 17:11:32 +02:00
if (typeof address !== 'string') {
2024-03-28 22:32:46 +01:00
throw new SyntaxError(
`missing key "address" in contact short name config for "${shortName}"`,
)
}
if (!(/\w+@(\w+\.)?cohabit\.fr/.test(address))) {
throw new SyntaxError(
`invalid "address" in contact short name config for "${shortName}"`,
)
}
//@ts-ignore checked against regex
return new Contact({ name, address })
}
static fromString(raw: string): Contact {
const [_, name, address] =
raw.match(/(.*)<(\S+@\S+\.\S+)>/)?.map((match) => match.trim()) ?? []
if (typeof address !== 'string') {
throw new Error('address is empty')
}
//@ts-ignore checked against regex
return new Contact({ name, address })
}
toString(): string {
return `${this.#name} <${this.#address}>`
}
toJSON() {
return {
name: this.#name,
address: this.#address,
} as const
}
get name() {
return this.#name
}
get address() {
return this.#address
}
}