( key: K, store: EntityStore<D, V>, cleanup: CleanupObject )
| 58 | * Will create unique key index for entity store that will automatically add/update/delete items from the index on changes. |
| 59 | */ |
| 60 | export function createQueryFieldIndex< |
| 61 | D, |
| 62 | V, |
| 63 | K extends keyof IndexableData<D & V> |
| 64 | >( |
| 65 | key: K, |
| 66 | store: EntityStore<D, V>, |
| 67 | cleanup: CleanupObject |
| 68 | ): QueryIndex<D, V, K> { |
| 69 | type TargetEntity = Entity<D, V>; |
| 70 | type TargetValue = IndexableData<TargetEntity>[K]; |
| 71 | type TargetValueInput = IndexValueInput<TargetValue>; |
| 72 | |
| 73 | /** |
| 74 | * Index map. Example: topic has slug. Lets say we have 2 slugs 'foo' and 'bar'. |
| 75 | * |
| 76 | * This map would be like: |
| 77 | * { |
| 78 | * foo: entity1, |
| 79 | * bar: entity2 |
| 80 | * } |
| 81 | */ |
| 82 | const observableIndex = observable.map< |
| 83 | TargetValue, |
| 84 | IObservableArray<TargetEntity> |
| 85 | >({}); |
| 86 | |
| 87 | function getCurrentIndexValue(entity: TargetEntity): TargetValue { |
| 88 | return entity[key] as TargetValue; |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Map keeping info to what index 'page' item currently belongs to |
| 93 | */ |
| 94 | const currentItemIndexMap = new WeakMap< |
| 95 | TargetEntity, |
| 96 | IObservableArray<Entity<D, V>> |
| 97 | >(); |
| 98 | |
| 99 | try { |
| 100 | set(window, `__index.${store.definition.config.name}.${key.toString()}`, { |
| 101 | observableIndex, |
| 102 | }); |
| 103 | } catch (error) { |
| 104 | // |
| 105 | } |
| 106 | |
| 107 | function updateItemIndexWithValue( |
| 108 | entity: TargetEntity, |
| 109 | indexValue: TargetValue |
| 110 | ) { |
| 111 | // Item might already be indexed somewhere |
| 112 | const currentIndexList = currentItemIndexMap.get(entity); |
| 113 | // Get where it should be indexed now |
| 114 | const targetIndexList = observableMapGetOrCreate( |
| 115 | observableIndex, |
| 116 | indexValue, |
| 117 | () => observable.array() |
no test coverage detected