1 | import { StringElement } from 'minim';
|
---|
2 | import stampit from 'stampit';
|
---|
3 | import ShortUniqueId from 'short-unique-id';
|
---|
4 | import ElementIdentityError from "./errors/ElementIdentityError.mjs";
|
---|
5 | import { isElement, isStringElement } from "../predicates/index.mjs";
|
---|
6 | // @TODO(oliwia.rogala@smartbear.com): transforming this stamp to class will break backward compatibility
|
---|
7 | export const IdentityManager = stampit({
|
---|
8 | props: {
|
---|
9 | uuid: null,
|
---|
10 | length: null,
|
---|
11 | identityMap: null
|
---|
12 | },
|
---|
13 | init({
|
---|
14 | length = 6
|
---|
15 | } = {}) {
|
---|
16 | this.length = 6;
|
---|
17 | this.uuid = new ShortUniqueId({
|
---|
18 | length
|
---|
19 | });
|
---|
20 | this.identityMap = new WeakMap();
|
---|
21 | },
|
---|
22 | methods: {
|
---|
23 | identify(element) {
|
---|
24 | if (!isElement(element)) {
|
---|
25 | throw new ElementIdentityError('Cannot not identify the element. `element` is neither structurally compatible nor a subclass of an Element class.', {
|
---|
26 | value: element
|
---|
27 | });
|
---|
28 | }
|
---|
29 |
|
---|
30 | // use already assigned identity
|
---|
31 | if (element.meta.hasKey('id') && isStringElement(element.meta.id) && !element.meta.id.equals('')) {
|
---|
32 | return element.id;
|
---|
33 | }
|
---|
34 |
|
---|
35 | // assign identity in immutable way
|
---|
36 | if (this.identityMap.has(element)) {
|
---|
37 | return this.identityMap.get(element);
|
---|
38 | }
|
---|
39 |
|
---|
40 | // return element identity
|
---|
41 | const id = new StringElement(this.generateId());
|
---|
42 | this.identityMap.set(element, id);
|
---|
43 | return id;
|
---|
44 | },
|
---|
45 | forget(element) {
|
---|
46 | if (this.identityMap.has(element)) {
|
---|
47 | this.identityMap.delete(element);
|
---|
48 | return true;
|
---|
49 | }
|
---|
50 | return false;
|
---|
51 | },
|
---|
52 | generateId() {
|
---|
53 | return this.uuid.randomUUID();
|
---|
54 | }
|
---|
55 | }
|
---|
56 | });
|
---|
57 | export const defaultIdentityManager = IdentityManager({
|
---|
58 | length: 6
|
---|
59 | }); |
---|