refactor(model): ♻️ refactor Machine model to remove URL class attributes

This commit is contained in:
Julien Oculi 2024-06-17 18:15:47 +02:00
parent 6d08698d10
commit f0899797d8

View file

@ -1,14 +1,12 @@
import { Ref } from '@/src/models/utils/ref.ts'
import type { ToJson } from '@/types.ts'
import type { ToJson, UrlString } from '@/types.ts'
import type { Group } from '@models/group.ts'
import { Ressource } from '@models/ressource.ts'
export class Machine extends Ressource {
static fromJSON(
json: ToJson<Machine>,
{ url, avatar, ...json }: ToJson<Machine>,
): Machine {
const url = new URL(json.url)
const avatar = new URL(json.avatar)
const groups = json.groups.map((group) => Ref.fromString<Group>(group))
return new Machine({ ...json, url, avatar, groups })
@ -23,7 +21,7 @@ export class Machine extends Ressource {
}
#tags: readonly string[]
#url: URL
#url: UrlString
#status:
| 'ready'
| 'busy'
@ -31,7 +29,7 @@ export class Machine extends Ressource {
| 'discontinued'
| 'error'
| 'unknown'
#avatar: URL
#avatar: UrlString
#groups: readonly Ref<Group>[]
private constructor(
@ -42,14 +40,14 @@ export class Machine extends Ressource {
super(props)
this.#tags = Object.freeze(tags)
this.#url = new URL(url)
this.#url = new URL(url).href as UrlString
if (!['working', 'pending', 'ready', 'unavailable'].includes(status)) {
throw new TypeError(
`status is "${status}" but ('ready' | 'busy' | 'unavailable' | 'discontinued' | 'error' | 'unknown') is required`,
)
}
this.#status = status
this.#avatar = new URL(avatar)
this.#avatar = new URL(avatar).href as UrlString
this.#groups = Object.freeze(groups)
}
@ -57,16 +55,16 @@ export class Machine extends Ressource {
return 'machine'
}
get tags() {
return this.#tags.slice()
return this.#tags
}
get url() {
return new URL(this.#url)
return this.#url
}
get status() {
return this.#status
}
get avatar() {
return new URL(this.#avatar)
return this.#avatar
}
get groups() {
return this.#groups
@ -84,10 +82,10 @@ export class Machine extends Ressource {
return {
...super.toJSON(),
type: this.type,
tags: this.tags.slice(),
url: this.url.toJSON(),
tags: this.tags,
url: this.url,
status: this.status,
avatar: this.avatar.toJSON(),
avatar: this.avatar,
groups: Object.freeze(this.groups.map((group) => group.toJSON())),
} as const
}
@ -99,8 +97,8 @@ export class Machine extends Ressource {
export interface Machine extends Ressource {
type: 'machine'
tags: string[]
url: URL
tags: readonly string[]
url: UrlString
status:
| 'ready'
| 'busy'
@ -108,6 +106,6 @@ export interface Machine extends Ressource {
| 'discontinued'
| 'error'
| 'unknown'
avatar: URL
avatar: UrlString
groups: readonly Ref<Group>[]
}