-
Notifications
You must be signed in to change notification settings - Fork 4
UserManager abstraction added #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Reversean
wants to merge
2
commits into
master
Choose a base branch
from
refactor/user-manager
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+285
−43
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| export type { HawkStorage } from './storages/hawk-storage'; | ||
| export type { RandomGenerator } from './utils/random' | ||
| export { HawkUserManager } from './users/hawk-user-manager'; | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import type { AffectedUser } from '@hawk.so/types'; | ||
| import type { HawkStorage } from '../storages/hawk-storage'; | ||
| import { id } from "../utils/id"; | ||
| import { RandomGenerator } from "../utils/random"; | ||
|
Check warning on line 4 in packages/core/src/users/hawk-user-manager.ts
|
||
|
|
||
| /** | ||
| * Storage key used to persist the auto-generated user ID. | ||
| */ | ||
| const SESSION_STORAGE_KEY = 'hawk-user-id'; | ||
|
|
||
| /** | ||
| * Manages the affected user identity. | ||
| * | ||
| * Manually provided users are kept in memory only (they don't change restarts). | ||
| * {@link HawkStorage} is used solely to persist the auto-generated ID | ||
| * so it survives across sessions. | ||
| * | ||
| * @remarks changes to user data in storage from outside manager are not tracked; | ||
| * for changes to take effect call {@link clear}. | ||
| */ | ||
| export class HawkUserManager { | ||
| /** | ||
| * In-memory user set explicitly via {@link setUser}. | ||
| */ | ||
| private user: AffectedUser | null = null; | ||
|
|
||
| /** | ||
| * Underlying storage used to persist auto-generated user ID. | ||
| */ | ||
| private readonly storage: HawkStorage; | ||
|
|
||
| /** | ||
| * Random generator used to produce anonymous user IDs. | ||
| */ | ||
| private readonly randomGenerator: RandomGenerator; | ||
|
|
||
| /** | ||
| * @param storage - storage backend to use for persistence | ||
| * @param randomGenerator - utilities related to RandomGenerator generated values | ||
| */ | ||
| constructor( | ||
| storage: HawkStorage, | ||
| randomGenerator: RandomGenerator, | ||
| ) { | ||
| this.storage = storage; | ||
| this.randomGenerator = randomGenerator; | ||
| } | ||
|
|
||
| /** | ||
| * Returns current affected user if set, otherwise generates and persists an anonymous ID. | ||
| * | ||
| * Priority: in-memory user > persisted user ID. | ||
| * | ||
| * @return set affected user or user with generated ID | ||
| */ | ||
| public getUser(): AffectedUser { | ||
| if (this.user) { | ||
| return this.user; | ||
| } | ||
|
|
||
| let storedId = this.storage.getItem(SESSION_STORAGE_KEY); | ||
| if (!storedId) { | ||
| storedId = id(this.randomGenerator) | ||
| this.storage.setItem(SESSION_STORAGE_KEY, storedId); | ||
| } | ||
|
|
||
| this.user = { id: storedId } | ||
|
|
||
| return this.user!; | ||
| } | ||
|
|
||
| /** | ||
| * Sets the user explicitly (in memory only). | ||
| * | ||
| * @param user - The affected user provided by the application. | ||
| */ | ||
| public setUser(user: AffectedUser): void { | ||
| this.user = user; | ||
| } | ||
|
|
||
| /** | ||
| * Clears the explicitly set user, falling back to the persisted user ID. | ||
| */ | ||
| public clear(): void { | ||
| this.user = null; | ||
| } | ||
| } | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { RandomGenerator } from "./random"; | ||
|
Check warning on line 1 in packages/core/src/utils/id.ts
|
||
|
|
||
| /** | ||
|
Check warning on line 3 in packages/core/src/utils/id.ts
|
||
| * Returns random string | ||
| */ | ||
| export function id(random: RandomGenerator): string { | ||
| const validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | ||
|
|
||
| const randomSequence = random | ||
| .getRandomNumbers(40) | ||
| .map(x => validChars.charCodeAt(x % validChars.length)); | ||
|
|
||
| return String.fromCharCode.apply(null, randomSequence); | ||
| } | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| /** | ||
| * Abstraction over random value generator. | ||
| * Allows platform-specific implementations to be injected wherever random values are needed. | ||
| */ | ||
| export interface RandomGenerator { | ||
| /** | ||
| * Generates sequence of random unsigned numbers. | ||
| * | ||
| * @param length - Length of generated sequence. | ||
| * @returns Array filled with random unsigned numbers. | ||
| */ | ||
| getRandomNumbers(length: number): Uint8Array<ArrayBuffer>; | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { describe, it, expect, beforeEach, vi } from 'vitest'; | ||
| import { HawkUserManager } from '../../src'; | ||
| import type { HawkStorage, RandomGenerator } from '../../src'; | ||
|
|
||
| describe('HawkUserManager', () => { | ||
| let storage: HawkStorage; | ||
| let randomGenerator: RandomGenerator; | ||
| let manager: HawkUserManager; | ||
|
|
||
| beforeEach(() => { | ||
| storage = { | ||
| getItem: vi.fn().mockReturnValue(null), | ||
| setItem: vi.fn(), | ||
| removeItem: vi.fn(), | ||
| }; | ||
| randomGenerator = { | ||
| getRandomNumbers: vi.fn().mockReturnValue(new Uint8Array(40).fill(42)), | ||
| }; | ||
| manager = new HawkUserManager(storage, randomGenerator); | ||
| }); | ||
|
|
||
| it('should return anonymous ID when no user is set and no ID is persisted', () => { | ||
| const user = manager.getUser(); | ||
|
|
||
| expect(user.id).toBeTruthy(); | ||
| expect(storage.setItem).toHaveBeenCalledWith('hawk-user-id', user.id); | ||
| }); | ||
|
|
||
| it('should return in-memory user set via setUser()', () => { | ||
| const user = { id: 'user-1', name: 'Ryan Gosling', url: 'https://example.com', photo: 'https://example.com/photo.png' }; | ||
|
|
||
| manager.setUser(user); | ||
|
|
||
| expect(manager.getUser()).toEqual(user); | ||
| expect(storage.setItem).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should not affect storage when setUser() is called', () => { | ||
| manager.setUser({ id: 'user-1' }); | ||
|
|
||
| expect(storage.setItem).not.toHaveBeenCalled(); | ||
| expect(storage.removeItem).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return anonymous user from storage when no in-memory user is set', () => { | ||
| vi.mocked(storage.getItem).mockReturnValue('anon-123'); | ||
|
|
||
| expect(manager.getUser()).toEqual({ id: 'anon-123' }); | ||
| expect(storage.getItem).toHaveBeenCalledWith('hawk-user-id'); | ||
| }); | ||
|
|
||
| it('should prefer in-memory user over persisted anonymous ID', () => { | ||
| vi.mocked(storage.getItem).mockReturnValue('anon-123'); | ||
| manager.setUser({ id: 'explicit-user' }); | ||
|
|
||
| expect(manager.getUser()).toEqual({ id: 'explicit-user' }); | ||
| }); | ||
|
|
||
| it('should clear in-memory user and fall back to persisted anonymous ID', () => { | ||
| vi.mocked(storage.getItem).mockReturnValue('anon-123'); | ||
| manager.setUser({ id: 'user-1' }); | ||
| manager.clear(); | ||
|
|
||
| expect(manager.getUser()).toEqual({ id: 'anon-123' }); | ||
| }); | ||
|
|
||
| it('should return new anonymous ID after clear() when no ID is persisted', () => { | ||
| manager.setUser({ id: 'user-1' }); | ||
| manager.clear(); | ||
|
|
||
| const user = manager.getUser(); | ||
|
|
||
| expect(user.id).toBeTruthy(); | ||
| expect(storage.setItem).toHaveBeenCalledWith('hawk-user-id', user.id); | ||
| }); | ||
| }); |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "extends": "./tsconfig.json", | ||
| "compilerOptions": { | ||
| "outDir": null, | ||
| "declaration": false, | ||
| "types": ["vitest/globals"] | ||
| }, | ||
| "include": [ | ||
| "src/**/*", | ||
| "tests/**/*", | ||
| "vitest.config.ts" | ||
| ] | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import { defineConfig } from 'vitest/config'; | ||
|
|
||
| export default defineConfig({ | ||
| test: { | ||
| globals: true, | ||
| include: ['tests/**/*.test.ts'], | ||
| typecheck: { | ||
| tsconfig: './tsconfig.test.json', | ||
| }, | ||
| coverage: { | ||
| provider: 'v8', | ||
| include: ['src/**/*.ts'], | ||
| }, | ||
| }, | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.