Anyone who knows me, knows I 😍😍 Firebase. It could be considered unhealthy 😂. Despite my love for it, I have had my fair share of disagreements with it. The biggest one that comes to mind relates to Firestore.
NOTE: This article assumes you have a basic knowledge of how Firestore works. (docs)
This article will contain:
- 🤔 The Problem — Something that annoyed me
- 💪 My Solution — A brief overview
- 🤩 LET’S BUILD! — Party time! 🎉🎉
🤔 The Problem
The examples all tend to start with your call to the
collection method in your
Component to ensure you are working with the correct collection in Firestore. But all these calls to
collection add up. There must be a better way?
💪 My Solution
To me, there is! But, this is subjective. I create a Generic Firebase CRUD Service*, that accepts a Type to define the model that I want to store in my Collection on Firestore.
This is what we are going to build in this article!
* I call this a service, but it is unlike a standard Angular Service that can be injected into a
constructor, rather it is simply an instantiated class.
🤩 LET’S BUILD!
Ok, before we begin, let me take a moment to state that when I do this in codebases I work on, I tend to use the Bridge Pattern, by setting up a base Implementation for the CRUD Service, then define a Concrete Implementation of this, specific to Firetore.
My Abstractions have reference to the base Implementation but use the Firestore Concrete Implementation.
If any of this seems confusing, I highly recommend you read the Bridge Pattern article linked!
We’ll break this build down into a few steps:
- Setup — Setting up the class!
- Create — The code to add the Document (henceforth called the Entity)