Skip to content

Commit

Permalink
Fix TS for firebase + remove globals.d.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
stevie.hartog committed Jun 14, 2024
1 parent edda024 commit d53d863
Show file tree
Hide file tree
Showing 12 changed files with 345 additions and 379 deletions.
546 changes: 275 additions & 271 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@
"devDependencies": {
"@playwright/test": "^1.44.1",
"@rushstack/eslint-patch": "^1.10.3",
"@storybook/addon-essentials": "^8.1.8",
"@storybook/vue3-vite": "^8.1.8",
"@storybook/addon-essentials": "^8.1.9",
"@storybook/vue3-vite": "^8.1.9",
"@tsconfig/node20": "^20.1.4",
"@types/digital-goods-browser": "^2.0.3",
"@types/google.maps": "^3.55.9",
Expand All @@ -69,7 +69,7 @@
"rollup-plugin-visualizer": "^5.12.0",
"sass": "^1.77.5",
"typescript": "~5.4.0",
"vite": "^5.3.0",
"vite": "^5.3.1",
"vite-plugin-pwa": "^0.20.0",
"vite-plugin-vue-devtools": "^7.2.1",
"vite-plugin-vuetify": "^2.0.3",
Expand Down
61 changes: 0 additions & 61 deletions src/globals.d.ts

This file was deleted.

1 change: 1 addition & 0 deletions src/interfaces/activities.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* Represents an activity done by a user.
*/
export interface Activity {
id?: string
/** The name of the activity */
name: string
/** The local start date and time of the activity */
Expand Down
28 changes: 18 additions & 10 deletions src/plugins/firebase/generic-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import {
CollectionReference,
DocumentReference,
WhereFilterOp,
OrderByDirection
OrderByDirection,
DocumentSnapshot,
startAfter
} from 'firebase/firestore/lite'
import { toRaw, isRef, isReactive, isProxy } from 'vue'
import firebaseApp from '@/plugins/firebase'
Expand All @@ -45,8 +47,8 @@ export function deepToRaw(sourceObj: any): any {

const db: Firestore = getFirestore(firebaseApp)

export default class GenericDB {
private collectionPath: string
export default class GenericDB<T> {
public collectionPath: string

constructor(collectionPath: string) {
this.collectionPath = collectionPath
Expand All @@ -56,7 +58,7 @@ export default class GenericDB {
* @param data
* @param id
*/
async create(data: any, id: string | null = null): Promise<{ id: string; [key: string]: any }> {
async create(data: any, id?: string | null): Promise<T> {
const collectionRef: CollectionReference = collection(db, this.collectionPath)
const serverTimestampA = serverTimestamp()

Expand All @@ -81,14 +83,14 @@ export default class GenericDB {
...data,
createTimestamp: new Date(),
updateTimestamp: new Date()
}
} as T
}

/**
* Read a document in the collection
* @param id
*/
async read(id: string): Promise<{ id: string; [key: string]: any } | null> {
async read(id: string): Promise<(T & { id: string }) | null> {
const docRef: DocumentReference = doc(db, this.collectionPath, id)
const result = await getDoc(docRef)

Expand All @@ -98,7 +100,7 @@ export default class GenericDB {

this.convertObjectTimestampPropertiesToDate(data)

return { id, ...data }
return { id, ...data } as T & { id: string }
}

/**
Expand All @@ -108,13 +110,15 @@ export default class GenericDB {
* @param {string | null} order - Field to sort the results by.
* @param {OrderByDirection} direction - Field to manage the order direction.
* @param {number | null} amount - Maximum number of documents to retrieve.
* @param {DocumentSnapshot | null} lastVisible - Last visible document from the previous query.
* @returns {Promise<any[]>} - Array of documents retrieved.
*/
async readAll(
constraints: Array<[string, WhereFilterOp, any]> | null = null,
order: string | null = null,
direction: OrderByDirection = 'desc',
amount: number | null = null
amount: number | null = null,
lastVisible: DocumentSnapshot | null = null
): Promise<any[]> {
const collectionRef: CollectionReference = collection(db, this.collectionPath)

Expand All @@ -130,15 +134,19 @@ export default class GenericDB {
combinedQuery.push(orderBy(order, direction))
}

if (amount) {
if (lastVisible) {
combinedQuery.push(startAfter(lastVisible))
}

if (amount !== null) {
combinedQuery.push(limit(amount))
}

if (combinedQuery.length > 0) {
q = query(collectionRef, ...combinedQuery)
}

const formatResult = (result: any) =>
const formatResult = (result: any): any =>
result.docs.map((ref: any) =>
this.convertObjectTimestampPropertiesToDate({
id: ref.id,
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/firebase/user-activities-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import GenericDB from './generic-db'
import { Activity } from '@/interfaces/activities.interface'

export default class UserActivitiesDB extends GenericDB {
export default class UserActivitiesDB extends GenericDB<Activity> {
constructor(userId: string) {
super(`users/${userId}/activities`)
}
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/firebase/user-workouts-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Workout } from '@/interfaces/workouts.interface'
import GenericDB from './generic-db'

export default class UserWorkoutsDB extends GenericDB {
export default class UserWorkoutsDB extends GenericDB<Workout> {
constructor(userId: string) {
super(`users/${userId}/workouts`)
}
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/firebase/users-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { User } from '@/interfaces/authentication.interface'
import GenericDB from './generic-db'

export default class UsersDB extends GenericDB {
export default class UsersDB extends GenericDB<User> {
constructor() {
super('users')
}
Expand Down
9 changes: 5 additions & 4 deletions src/plugins/firebase/users-workouts-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ import {
} from 'firebase/firestore/lite'
import firebaseApp from '@/plugins/firebase'
import GenericDB from '@/plugins/firebase/generic-db'
import { Workout } from '@/interfaces/workouts.interface'

const db: Firestore = getFirestore(firebaseApp)

export default class UsersWorkoutsDB extends GenericDB {
export default class UsersWorkoutsDB extends GenericDB<Workout> {
constructor() {
super('users')
}
Expand All @@ -29,16 +30,16 @@ export default class UsersWorkoutsDB extends GenericDB {
* @param {Array<[string, WhereFilterOp, any]> | null} constraints - Array of constraints for the query.
* @param {string | null} order - Field to sort the results by.
* @param {OrderByDirection} direction - Field to manage the order direction.
* @param {DocumentSnapshot | null} lastVisible - Last visible document from the previous query.
* @param {number | null} amount - Maximum number of documents to retrieve.
* @param {DocumentSnapshot | null} lastVisible - Last visible document from the previous query.
* @returns {Promise<any[]>} - Array of documents retrieved.
*/
async readAll(
constraints: Array<[string, WhereFilterOp, any]> | null = null,
order: string | null = null,
direction: OrderByDirection = 'desc',
lastVisible: DocumentSnapshot | null = null,
amount: number | null = null
amount: number | null = null,
lastVisible: DocumentSnapshot | null = null
): Promise<any[]> {
const collectionRef = collectionGroup(db, 'workouts')

Expand Down
16 changes: 10 additions & 6 deletions src/stores/activities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ export const useActivitiesStore = defineStore('activities', () => {
async function fetchUserActivity() {
if (activities.value.length) return
const { user } = storeToRefs(useAuthenticationStore())
const userActivitiesDb = new UserActivitiesDB(user.value?.id)
activities.value = await userActivitiesDb.readAll(null, 'createTimestamp', 'desc', 20)
if (user.value) {
const userActivitiesDb = new UserActivitiesDB(user.value?.id)
activities.value = await userActivitiesDb.readAll(null, 'createTimestamp', 'desc', 20)
}
}
/**
* Add a new workout for the user
Expand All @@ -24,12 +26,14 @@ export const useActivitiesStore = defineStore('activities', () => {
*/
async function createUserActivity(activity: Activity) {
const { user } = storeToRefs(useAuthenticationStore())
const userActivitiesDb = new UserActivitiesDB(user.value?.id)
if (user.value) {
const userActivitiesDb = new UserActivitiesDB(user.value.id)

const createdActivity = await userActivitiesDb.create(activity)
const createdActivity = await userActivitiesDb.create(activity)

// push to beginning of workouts
activities.value.unshift(createdActivity)
// push to beginning of workouts
activities.value.unshift(createdActivity)
}
}

return {
Expand Down
6 changes: 3 additions & 3 deletions src/stores/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ export const useAuthenticationStore = defineStore('authentication', () => {
/**
* Create new user from firebase auth user infos
*/
async function createNewUserFromFirebaseAuthUser(firebaseAuthUser: FirebaseUser) {
async function createNewUserFromFirebaseAuthUser(firebaseAuthUser: FirebaseUser): Promise<User> {
let providerData = firebaseAuthUser.providerData[0]
if (firebaseAuthUser.isAnonymous) {
// eslint-disable-next-line prefer-destructuring
providerData = firebaseAuthUser
}
const { displayName, photoURL, email } = providerData
const { default: UsersDB } = await import('@/plugins/firebase/users-db')
const userDb = new UsersDB()
const usersDb = new UsersDB()
// default user settings
const settings: UserSettings = {
selected: 0,
Expand All @@ -46,7 +46,7 @@ export const useAuthenticationStore = defineStore('authentication', () => {
settings
}

return userDb.create(user, firebaseAuthUser.uid)
return usersDb.create(user, firebaseAuthUser.uid)
}
/**
* Callback fired when user login
Expand Down
42 changes: 24 additions & 18 deletions src/stores/workouts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export const useWorkoutsStore = defineStore('workouts', () => {
[['subscribers', 'array-contains', authentication.user?.id]],
'updateTimestamp',
'desc',
20,
// @ts-expect-error DocumentSnapshot
lastVisible,
20
lastVisible
)
workouts.value.push(...newWorkouts)
}
Expand All @@ -60,9 +60,9 @@ export const useWorkoutsStore = defineStore('workouts', () => {
constraints,
workoutsCommunityFilter.value.value,
'desc',
20,
// @ts-expect-error DocumentSnapshot
lastVisible,
20
lastVisible
)
workoutsCommunity.value.push(...newWorkouts)
}
Expand All @@ -75,7 +75,7 @@ export const useWorkoutsStore = defineStore('workouts', () => {
async function fetchLeaderboard(rank = 'completed.amount') {
if (leaderboards.value.find((leaderboard) => leaderboard.rank === rank)) return
const usersDb = new UsersDB()
const leaderboard = await usersDb.readAll([[rank, '>', 0]], rank, 15)
const leaderboard = await usersDb.readAll([[rank, '>', 0]], rank, 'desc', 15)
leaderboards.value.push({ rank, leaderboard })
}

Expand All @@ -86,16 +86,18 @@ export const useWorkoutsStore = defineStore('workouts', () => {
*/
async function createUserWorkout(workout: Workout) {
const { user } = storeToRefs(useAuthenticationStore())
const userWorkoutDb = new UserWorkoutsDB(user.value?.id)
if (user.value) {
const userWorkoutDb = new UserWorkoutsDB(user.value.id)

const createdWorkout = await userWorkoutDb.create(workout)
const createdWorkout = await userWorkoutDb.create(workout)

// push to beginning of workouts
workouts.value.unshift(createdWorkout)
// push to beginning of workouts
workouts.value.unshift(createdWorkout)

// also add the workout as a community workout
if (createdWorkout.share === true) {
workoutsCommunity.value.unshift(createdWorkout)
// also add the workout as a community workout
if (createdWorkout.share === true) {
workoutsCommunity.value.unshift(createdWorkout)
}
}
}

Expand All @@ -106,8 +108,10 @@ export const useWorkoutsStore = defineStore('workouts', () => {
*/
async function updateUserWorkout(payload: Workout) {
const { user } = storeToRefs(useAuthenticationStore())
const userWorkoutsDb = new UserWorkoutsDB(user.value?.id)
await userWorkoutsDb.update(payload)
if (user.value) {
const userWorkoutsDb = new UserWorkoutsDB(user.value.id)
await userWorkoutsDb.update(payload)
}
}

/**
Expand All @@ -117,13 +121,15 @@ export const useWorkoutsStore = defineStore('workouts', () => {
*/
async function removeUserWorkoutById(id: string) {
const { user } = storeToRefs(useAuthenticationStore())
const userWorkoutsDb = new UserWorkoutsDB(user.value?.id)
if (user.value) {
const userWorkoutsDb = new UserWorkoutsDB(user.value.id)

await userWorkoutsDb.delete(id)
await userWorkoutsDb.delete(id)

const index = workouts.value.findIndex((workout) => workout.id === id)
const index = workouts.value.findIndex((workout) => workout.id === id)

workouts.value.splice(index, 1)
workouts.value.splice(index, 1)
}
}

/**
Expand Down

0 comments on commit d53d863

Please sign in to comment.