Last active
September 25, 2023 14:57
-
-
Save mcgill-a/711607e67bd6877cb04be44fa52bcdfa to your computer and use it in GitHub Desktop.
A minimal backend user service
This file contains 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
export class UserService { | |
private _change = new Subject<UserChange>(); | |
private _users = new Map<string, User>(); | |
public readonly change = this._change.asObservable(); | |
public get users(): User[] { | |
return Array.from(this._users.values()); | |
} | |
public join(user: User): User { | |
if (this._users.get(user.email)) throw Error("User already exists"); | |
this._users.set(user.email, user); | |
this._change.next({ action: UserAction.join, user }); | |
return user; | |
} | |
public leave(user: User): void { | |
if (!this._users.get(user.email)) throw Error("User not found"); | |
this._users.delete(user.email); | |
this._change.next({ action: UserAction.leave, user }); | |
} | |
public position(updated: User): void { | |
const user = this._users.get(updated.email); | |
if (!user) throw Error("User not found. Can't update position"); | |
user.position = updated.position; | |
this._change.next({ action: UserAction.position, user }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment