From f7f3bbf0e0cf24286ceeb525cbf22a58cb4b164d Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Mon, 13 May 2024 17:15:13 +0200 Subject: [PATCH] refactor(model): :recycle: move default `ref` resolvers to static class methods --- src/models/utils/ref.ts | 68 ++++++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/src/models/utils/ref.ts b/src/models/utils/ref.ts index 586d67d..818e3c6 100644 --- a/src/models/utils/ref.ts +++ b/src/models/utils/ref.ts @@ -37,6 +37,40 @@ export class Ref extends String { return new Ref(Ref.parse(string)) } + static dbResolver(db: Db) { + return (ref: RefString) => { + const { type, uuid } = Ref.parse(ref) + return db.ressource[type].get({ uuid }) + } + } + + static restResolver(endpoint: string | URL) { + return async (ref: RefString) => { + 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 extends String { return this.toString() } } - -export function RefDbResolver(db: Db) { - return (ref: RefString) => { - const { type, uuid } = Ref.parse(ref) - return db.ressource[type].get({ uuid }) - } -} - -export function RefRestResolver(endpoint: string) { - return async (ref: RefString) => { - 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}"`) - } -}