Skip to content

Commit

Permalink
Created basic UserPrefs implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert-M-Lucas committed Apr 25, 2024
1 parent c0e73e5 commit 1d92705
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/utils/user_prefs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {describe, expect, test} from "vitest";
import {faker} from "@faker-js/faker";
import {UserPrefs, getUserPrefs, setUserPrefs} from "./user_prefs.ts";
import _ from "lodash";


describe("Firestore UserPrefs Tests", () => {
test("Read/Write/Default Value Test", async () => {
const user = { uid: faker.string.alphanumeric(20) }

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const prefs = await getUserPrefs(user);

expect(_.isEqual(prefs, UserPrefs.default()), "Non-existent UserPrefs should return default").toBeTruthy();

prefs.goal = 213;

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
await setUserPrefs(user, prefs);

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
const read_prefs = await getUserPrefs(user);

console.log(prefs);
console.log(read_prefs);

expect(_.isEqual(read_prefs, prefs), "UserPref changes to be read").toBeTruthy();
});
});
44 changes: 44 additions & 0 deletions src/utils/user_prefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {collection, doc, DocumentSnapshot, getDoc, setDoc, SnapshotOptions} from "firebase/firestore";
import {User} from "firebase/auth";
import {db} from "./firebase.ts";


export class UserPrefs {
public goal: number;

constructor(goal: number) {
this.goal = goal;
}

static default(): UserPrefs {
return new UserPrefs(100);
}

// Utility method for creating `Transactions`
static fromFirestore(snapshot: DocumentSnapshot, options: SnapshotOptions): UserPrefs {
const data = snapshot.data(options);
if (!data) {
throw Error("No data returned for snapshot!");
}
const u = new UserPrefs(data.goal);
return u;
}

toSendObject(): object {
const {...transObject} = this;
return transObject;
}
}

export async function getUserPrefs(user: User): Promise<UserPrefs> {
const docRef = doc(collection(db, "UserPrefs"), user.uid);

return await getDoc(docRef).then((ds) =>
UserPrefs.fromFirestore(ds, {})
).catch(() => UserPrefs.default());
}

export async function setUserPrefs(user: User, prefs: UserPrefs): Promise<void> {
const docRef = doc(collection(db, "UserPrefs"), user.uid);
await setDoc(docRef, prefs.toSendObject());
}

0 comments on commit 1d92705

Please sign in to comment.