Last active
June 17, 2022 10:55
-
-
Save NyaGarcia/025c296fde0b93826eff6db6060cfb13 to your computer and use it in GitHub Desktop.
Implementing CRUD functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
CollectionReference, | |
DocumentData, | |
addDoc, | |
collection, | |
deleteDoc, | |
doc, | |
updateDoc, | |
} from '@firebase/firestore'; | |
import { Firestore, collectionData, docData } from '@angular/fire/firestore'; | |
import { Injectable } from '@angular/core'; | |
import { Observable } from 'rxjs'; | |
interface Pokemon { | |
height: number; | |
id: string; | |
description: string; | |
imgUrl: string; | |
name: string; | |
type: string; | |
weight: number; | |
} | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class PokedexFirestoreService { | |
private pokemonCollection: CollectionReference<DocumentData>; | |
constructor(private readonly firestore: Firestore) { | |
this.pokemonCollection = collection(this.firestore, 'pokemon'); | |
} | |
getAll() { | |
return collectionData(this.pokemonCollection, { | |
idField: 'id', | |
}) as Observable<Pokemon[]>; | |
} | |
get(id: string) { | |
const pokemonDocumentReference = doc(this.firestore, `pokemon/${id}`); | |
return docData(pokemonDocumentReference, { idField: 'id' }); | |
} | |
create(pokemon: Pokemon) { | |
return addDoc(this.pokemonCollection, pokemon); | |
} | |
update(pokemon: Pokemon) { | |
const pokemonDocumentReference = doc( | |
this.firestore, | |
`pokemon/${pokemon.id}` | |
); | |
return updateDoc(pokemonDocumentReference, { ...pokemon }); | |
} | |
delete(id: string) { | |
const pokemonDocumentReference = doc(this.firestore, `pokemon/${id}`); | |
return deleteDoc(pokemonDocumentReference); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment