1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-10-30 08:10:34 +01:00
bitwarden-browser/libs/common/spec/fake-state-provider.ts
Matt Gibson e045c6b103
Ps/introduce single user state (#7053)
* Specify state provider for currently active user

* Split active and single user States

UserStateProvider is still the mechanism to build each State object.
The SingleUserState is basically a repeat of GlobalState, but with
additional scoping.

* Fixup global state cache

* fix fakers to new interface

* Make userId available in single user state

* Split providers by dependency requirements

This allows usage of the single state provider in contexts that would
otherwise form circular dependencies.

* Offer convenience wrapper classes for common use

* Import for docs

* Bind wrapped methods
2023-12-05 10:20:16 -05:00

64 lines
2.0 KiB
TypeScript

import {
GlobalState,
GlobalStateProvider,
KeyDefinition,
ActiveUserState,
SingleUserState,
} from "../src/platform/state";
import { UserId } from "../src/types/guid";
import { FakeActiveUserState, FakeGlobalState, FakeSingleUserState } from "./fake-state";
export class FakeGlobalStateProvider implements GlobalStateProvider {
states: Map<string, GlobalState<unknown>> = new Map();
get<T>(keyDefinition: KeyDefinition<T>): GlobalState<T> {
let result = this.states.get(keyDefinition.buildCacheKey("global")) as GlobalState<T>;
if (result == null) {
result = new FakeGlobalState<T>();
this.states.set(keyDefinition.buildCacheKey("global"), result);
}
return result;
}
getFake<T>(keyDefinition: KeyDefinition<T>): FakeGlobalState<T> {
return this.get(keyDefinition) as FakeGlobalState<T>;
}
}
export class FakeSingleUserStateProvider {
states: Map<string, SingleUserState<unknown>> = new Map();
get<T>(userId: UserId, keyDefinition: KeyDefinition<T>): SingleUserState<T> {
let result = this.states.get(keyDefinition.buildCacheKey("user", userId)) as SingleUserState<T>;
if (result == null) {
result = new FakeSingleUserState<T>(userId);
this.states.set(keyDefinition.buildCacheKey("user", userId), result);
}
return result;
}
getFake<T>(userId: UserId, keyDefinition: KeyDefinition<T>): FakeSingleUserState<T> {
return this.get(userId, keyDefinition) as FakeSingleUserState<T>;
}
}
export class FakeActiveUserStateProvider {
states: Map<string, ActiveUserState<unknown>> = new Map();
get<T>(keyDefinition: KeyDefinition<T>): ActiveUserState<T> {
let result = this.states.get(
keyDefinition.buildCacheKey("user", "active"),
) as ActiveUserState<T>;
if (result == null) {
result = new FakeActiveUserState<T>();
this.states.set(keyDefinition.buildCacheKey("user", "active"), result);
}
return result;
}
getFake<T>(keyDefinition: KeyDefinition<T>): FakeActiveUserState<T> {
return this.get(keyDefinition) as FakeActiveUserState<T>;
}
}