generated from PolymeshAssociation/typescript-boilerplate
/
Entity.ts
69 lines (59 loc) · 1.93 KB
/
Entity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { Context, PolymeshError } from '~/internal';
import { ErrorCode } from '~/types';
import { serialize, unserialize } from '~/utils/internal';
/**
* Represents an object or resource in the Polymesh Ecosystem with its own set of properties and functionality
*/
export abstract class Entity<UniqueIdentifiers, HumanReadable> {
/**
* Generate the Entity's UUID from its identifying properties
*
* @param identifiers
*/
public static generateUuid<Identifiers>(identifiers: Identifiers): string {
return serialize(this.name, identifiers);
}
/**
* Unserialize a UUID into its Unique Identifiers
*
* @param serialized - UUID to unserialize
*/
public static unserialize<Identifiers>(serialized: string): Identifiers {
const unserialized = unserialize<Identifiers>(serialized);
if (!this.isUniqueIdentifiers(unserialized)) {
throw new PolymeshError({
code: ErrorCode.InvalidUuid,
message: `The string doesn't correspond to the UUID of type ${this.name}`,
});
}
return unserialized;
}
/* istanbul ignore next: this function should always be overridden */
/**
* Typeguard that checks whether the object passed corresponds to the unique identifiers of the class. Must be overridden
*
* @param identifiers - object to type check
*/
public static isUniqueIdentifiers(identifiers: unknown): boolean {
return !!identifiers;
}
public uuid: string;
protected context: Context;
/**
* @hidden
*/
constructor(identifiers: UniqueIdentifiers, context: Context) {
this.uuid = (this.constructor as typeof Entity).generateUuid(identifiers);
this.context = context;
}
/**
* Whether this Entity is the same as another one
*/
public isEqual(entity: Entity<unknown, unknown>): boolean {
return this.uuid === entity.uuid;
}
/**
* Returns Entity data in a human readable (JSON) format
*/
public abstract toJson(): HumanReadable;
}