refactor(model): ♻️ move default ref resolvers to static class methods

This commit is contained in:
Julien Oculi 2024-05-13 17:15:13 +02:00
parent 8ae76d8254
commit f7f3bbf0e0

View file

@ -37,6 +37,40 @@ export class Ref<T extends Ressource> extends String {
return new Ref<T>(Ref.parse(string))
}
static dbResolver(db: Db) {
return <T extends Ressource>(ref: RefString<T>) => {
const { type, uuid } = Ref.parse(ref)
return db.ressource[type].get({ uuid })
}
}
static restResolver(endpoint: string | URL) {
return async <T extends Ressource>(ref: RefString<T>) => {
const { type, uuid } = Ref.parse(ref)
const url = new URL(`${type}/${uuid}`, endpoint)
const response = await fetch(url)
const json = await response.json()
if (type === 'user') {
return User.fromJSON(json)
}
if (type === 'machine') {
return Machine.fromJSON(json)
}
if (type === 'service') {
return Service.fromJSON(json)
}
if (type === 'group') {
return Group.fromJSON(json)
}
if (type === 'credential') {
return Credential.fromJSON(json)
}
throw new TypeError(`unknown ref type "${type}"`)
}
}
private constructor({ uuid, type }: { uuid: UUID; type: T['type'] }) {
super(Ref.#toString({ uuid, type }))
this.#type = type
@ -66,37 +100,3 @@ export class Ref<T extends Ressource> extends String {
return this.toString()
}
}
export function RefDbResolver(db: Db) {
return <T extends Ressource>(ref: RefString<T>) => {
const { type, uuid } = Ref.parse(ref)
return db.ressource[type].get({ uuid })
}
}
export function RefRestResolver(endpoint: string) {
return async <T extends Ressource>(ref: RefString<T>) => {
const { type, uuid } = Ref.parse(ref)
const url = new URL(`${type}/${uuid}`, endpoint)
const response = await fetch(url)
const json = await response.json()
if (type === 'user') {
return User.fromJSON(json)
}
if (type === 'machine') {
return Machine.fromJSON(json)
}
if (type === 'service') {
return Service.fromJSON(json)
}
if (type === 'group') {
return Group.fromJSON(json)
}
if (type === 'credential') {
return Credential.fromJSON(json)
}
throw new TypeError(`unknown ref type "${type}"`)
}
}