Reputation: 4057
I have a hard time getting my data right for Firebase and need some guidance. I'm confident around relational database and find that I'm just replicating that way of thinking to firebase.
I'm creating a fitness app. The structure I have is as follows: Exercises, Workouts and Programs.
Exercises is quite simple, it's a name, description and a photo of a simple movement, like squats or benchpressing.
exercise
--e1
--name:"Squats"
--description: "..."
--e2
--name:"Benchpress"
--description: "..."
Then I have a list of workouts. A workout is a set of exercises performed in a special order with specific reps and sets. One exercise could be used in many workouts with different parameters (reps, sets, rest)
workouts
--w1
--name:"Easy workout"
--description: "Design for beginners"
--exercises:
--we1:
--exercise: e1
--reps: 12
--rest: 60
--order: 1
--we2
--exercise: e2
--reps:6
--rest: 30
--order: 2
--w2
--name: "Hard exercise"
...
So here I have w1, a workout that just uses exercise 1: First you perform 12 reps of exercise 1, then rest for 60 seconds, then 6 reps of exercise 2 and rest for 30 seconds.
Finally I have a program/plan. A program consist of multiple workouts that you can follow. For example your program could consist of 3 workouts that you should on monday, wednesday and friday.
programs
--p1
--name: "The Stack Overflow Fitness Plan"
--description: "I am a fancy text"
--workouts:
--w1: true
--w2: true
So as stated above I'm just putting up relational data up in firebase. Which isn't the correct way. I just have trouble how I should maange this data in flat way. Are duplicates for example ok?
At the moment I have a really expensive read(not best practice) since I query the program location, map it, query the workouts, map it,query the exercises. It becomes quite cumbersome fast.
Any thoughs and help is greatly appreciated.
Upvotes: 1
Views: 84
Reputation: 2032
You could take a look into the normalizr
library. It was originally designed to help in working with rest API and redux : the same problem of duplication in a non relationnal environnement occurs.
Basically what I would do is have each different kind of entity stored as a Map in firebase.
const tree = {
exercises: { 1: { name: ... }, ... },
workouts: { 1: ... },
programs: { 1: ... },
}
Then you can have each of your components make subscriptions to their corresponding entity. With promises and/or streams it's pretty straightfoward.
Each of your relationships are simply an id in an Array and you can use the normalizr library to normalize / denormalize when you want to read / write in the db.
Note that with this pattern you can easily use the firebase update
api to update several entities at once using a query such as :
const updateQuery = {
"workouts/id": ...,
"exercises/id": ...,
"programs/id": ...,
}
Upvotes: 1