Modify Angular code to replace rtdb with firestore

We will replace the AngularFireDatabaseModule with AngularFirestoreModule. The category and tag services are pretty simple to convert.

The question and game service are interesting. Let’s cover the changes in those -

// question.service.ts ... getUserQuestions(user: User, published: boolean): Observable<Question[]> {

let collection = (published) ? "questions" : "unpublished_questions";

return this.db.collection(`/${collection}`, ref => ref.where('created_uid', '==', user.userId))

.valueChanges()

.map(qs => qs.map(q => Question.getViewModelFromDb(q)));

} saveQuestion(question: Question) {

let dbQuestion = Object.assign({}, question); //object to be saved let questionId = this.db.createId();

dbQuestion.id = questionId; //Use the set method of the doc instead of the add method on the collection, so the id field of the data matches the id of the document

this.db.doc('/unpublished_questions/' + questionId).set(dbQuestion).then(ref => {

this.store.dispatch(this.questionActions.addQuestionSuccess());

});

} approveQuestion(question: Question) {

let dbQuestion = Object.assign({}, question); //object to be saved let questionId = dbQuestion.id;

dbQuestion.status = QuestionStatus.APPROVED; //Transaction to remove from unpublished and add to published questions collection

this.db.firestore.runTransaction(transaction => {

return transaction.get(this.db.doc('/unpublished_questions/' + questionId).ref).then(doc =>

transaction.set(this.db.doc('/questions/' + questionId).ref, dbQuestion).delete(doc.ref)

);

})

}

...

The getUserQuestions above uses the where clause [where(‘created_uid’, ‘==’, user.userId))] to get the questions for the user.

The saveQuestion uses “this.db.createId()” to first get the id for the question. It then uses this as the id of the document to be created. Note the use of Object.assign to convert the instance of a Typescript class to a pure object that can be persisted in the database.

The approveQuestion makes uses of a transaction to create a new document in questions collection and delete it from the unpublished_questions collection.

The game service makes use of the update method as below -

The rest of the service method uses code similar to one of the above scenarios. For code changes to all the services, check out the github repo commit.