Created
January 9, 2024 23:01
-
-
Save zerkalica/04030dd360db4cea8611631e6c4884fe to your computer and use it in GitHub Desktop.
entity.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace $ { | |
const str = () => ('00000000000000000' + (Math.random() * 0xffffffffffffffff).toString(16)).slice(-16) | |
export class $gd_kit_entity extends $mol_object { | |
constructor(id?: string) { | |
super() | |
if (id) this.id = $mol_const(id) | |
} | |
// p-ка свойства-объекта | |
@ $mol_mem | |
id(): string { | |
throw new Error('setup') | |
} | |
protected static create_uuid() { | |
const a = str() | |
const b = str() | |
return a.slice(0, 8) + '-' + a.slice(8, 12) + '-4' + a.slice(13) + '-a' + b.slice(1, 4) + '-' + b.slice(4) | |
} | |
@ $mol_action | |
static create_id(group = ''): string { | |
const is_secure = this.$.$mol_dom_context.isSecureContext | |
return is_secure ? this.$.$mol_crypto_uuid() : this.create_uuid() | |
} | |
@ $mol_action | |
static created_at(group = '') { | |
return new Date().toISOString() | |
} | |
@ $mol_mem | |
data( patch?: {} | undefined | null) { | |
return {} as {} | null | |
} | |
@ $mol_mem | |
protected draft(next?: ReturnType<typeof this.data> | null) { | |
return next ?? null | |
} | |
@ $mol_mem_key | |
value< | |
Field extends keyof NonNullable<ReturnType< this['data'] >> | |
>( | |
field: Field, | |
value?: NonNullable<ReturnType< this['data'] >>[ Field ] | null, | |
): NonNullable<ReturnType< this['data'] >>[ Field ] | null | undefined { | |
const data = this.draft() ?? this.data() | |
if (value === undefined) return data?.[field as never] | |
const next = { ...data, [ field ]: value } | |
this.draft(next) | |
try { | |
const result = this.data( next )?.[ field as never ] | |
this.draft(null) | |
return result | |
} catch (e) { | |
if (e instanceof Error) this.draft(null) | |
$mol_fail_hidden(e) | |
} | |
} | |
@ $mol_mem | |
title(next?: string | null) { | |
return next | |
} | |
@ $mol_mem | |
created_at(next?: $mol_time_moment | string) { | |
return next ?? new this.$.$mol_time_moment | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment