Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Firestoreを実装してみた話

keinuma
January 05, 2021
47

 Firestoreを実装してみた話

keinuma

January 05, 2021
Tweet

Transcript

  1. Firestore の使い 照 Collection と 件を指 して 索 更 を

    知できる ・更 Document 単 で 6 / 16
  2. 照 import * as firebase from 'firebase/app' const firestore =

    firebase.firestore() const collection = firestore.collection('messages') collection .where('uids', 'array-contains', 'xxxx-xxx-xxx') .get() .then((document) => { const data = document.data() console.log(data) }) 7 / 16
  3. 照( 更を 知) const firestore = firebase.firestore() const collection =

    firestore.collection('messages') const unsubscribe = collection .where('uids', 'array-contains', 'xxxx-xxx-xxx') .onSnapshot() .then((snapshot) => { const data = snapshot.data() console.log(data) }) window.addEventListener('unload', unsubscribe) 8 / 16
  4. const converter = { toFirestore(messageModel) { return { ...messageModel, updatedAt:

    firestore.Timestamp.fromDate(messageModel.updatedAt) } }, fromFirestore(snapshot) { const messageData = snapshot.data() return new MessageModel({ ...messageData, updatedAt: messageData.updatedAt.toDate() }) } } const convertCollection = collection.withConverter(converter) 11 / 16
  5. Firestore のメソッドをラップ class FirestoreRepository { private readonly collection constructor(path, converter)

    { this.collection = db.collection(path) .withConverter(converter) } subscribeById(id, callback) { return this.collection.doc(id).onSnapshot( (snapshot) => callback(snapshot.data()) ) } } 14 / 16
  6. ドメイン別に を 義 const converter = { toFirestore(messageModel) { ...

    }, fromFirestore(snapshot) { ... } } const MessagesRepository = new FirestoreRepository( 'messages', converter ) 15 / 16