Skip to content

Instantly share code, notes, and snippets.

@mcgill-a
Last active September 25, 2023 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcgill-a/711607e67bd6877cb04be44fa52bcdfa to your computer and use it in GitHub Desktop.
Save mcgill-a/711607e67bd6877cb04be44fa52bcdfa to your computer and use it in GitHub Desktop.
A minimal backend user service
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