Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Last active June 17, 2022 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NyaGarcia/025c296fde0b93826eff6db6060cfb13 to your computer and use it in GitHub Desktop.
Save NyaGarcia/025c296fde0b93826eff6db6060cfb13 to your computer and use it in GitHub Desktop.
Implementing CRUD functions
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