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

Firestoreをもっと手軽に使えるfirestore-simpleを作った

 Firestoreをもっと手軽に使えるfirestore-simpleを作った

Kenta Kase

July 02, 2018
Tweet

More Decks by Kenta Kase

Other Decks in Programming

Transcript

  1. 1Πϯελϯε1ίϨΫγϣϯ • ຖճίϨΫγϣϯ΁ͷύεΛॻ͘ͷ͸ΊΜͲ͍͘͞ • ඒ͘͠ͳ͍ͷͰ݁ہࣗ෼ͰίϨΫγϣϯ͝ͱͷ ModelͳͲΛ࡞Δ͜ͱʹͳΔ const firestore = admin.firestore()

    const collectionPath = 'users' await firestore.collection(collectionPath).add({ name: 'alice', age: 20 }) await firestore.collection(collectionPath).add({ name: 'bob', age: 22 }) const user_documents = await firestore.collection(collectionPath).get() ૉͷFirestore
  2. 1Πϯελϯε1ίϨΫγϣϯ • ίϨΫγϣϯύεΛ౉ͯ͠ΠϯελϯεΛ࡞Δ • ຖճίϨΫγϣϯύεΛ౉͢ඞཁ͕ͳ͍ const firestore = admin.firestore() const

    collectionPath = 'users' const dao = new FirestoreSimple(firestore, collectionPath) await dao.add({ name: 'alice', age: 20}) await dao.add({ name: 'bob', age: 22 }) firestore-simple
  3. ී௨ͷObjectΛฦ͢ • ϑΣονͨ͠υΩϡϝϯτͷத਎ɿ doc.data() • υΩϡϝϯτͷid: doc.id • όϥόϥͳͷͰ࢖͍উख͕͍·͍ͪ const

    doc = await firestore.collection(collectionPath).doc(id).get() const id = doc.id const name = doc.data().name ૉͷFirestore
  4. ී௨ͷObjectΛฦ͢ • ϑΣονͷ݁Ռ͸ී௨ͷObjectΛฦ͢ • idͱͦΕҎ֎Ͱݺͼग़͠ํ͕ಉ͡ • αϯϓϧίʔυͰ͸doc.id, doc.name • add΍setͰ΋ObjectΛฦ͢

    const doc = await dao.fetchDocument(id) // { id: 'XoZBjNpnj6QKCXSW4bu7', name: 'alice', age: 20 } const addedDoc = await dao.add({ name: ‘alice', age: 20}) // { id: 'XoZBjNpnj6QKCXSW4bu7', name: 'alice', age: 20 } firestore-simple
  5. ී௨ͷArrayΛฦ͢ • ίϨΫγϣϯͷυΩϡϝϯτΛෳ਺ϑΣονͨ͠ ৔߹͸forEach͔͠࢖͑ͳ͍ • ໭Γ஋͸ArrayͰ͸ͳͯ͘QuerySnapshotͳͨΊ • map΍filter͕࢖͑ͳ͍ͷ͸͔ͳΓෆศ const userDocuments

    = await firestore.collection(collectionPath).get() const users = [] userDocuments.forEach((document) => { const data = document.data() users.push({ id: document.id, name: data.name, age: data.age }) }) ૉͷFirestore
  6. ී௨ͷArrayΛฦ͢ • ෳ਺ϑΣονͨ͠৔߹͸ී௨ͷArrayΛฦ͢ • mapͳͲ͕࢖͑ΔͷͰίʔυ͕εοΩϦ͢Δ const users = await dao.fetchCollection()

    // [ { id: '3mBYA0uXw0lw6b883jgk', age: 20, name: 'alice' }, // { id: 'lE9SfP8f3H8w0Uwk0euQ', age: 22, name: 'bob' } ] const ids = users.map((user) => user.id) firestore-simple
  7. ϝιουҰཡ • fetchDocument • fetchCollection • fetchByQueryʢwhere, order by, limitʣ

    • add • set • addOrSetʢfirestore-simpleΦϦδφϧʣ • delete • bulkSetʢbatchʹΑΔҰׅsetʣ • bulkDeleteʢbatchʹΑΔҰׅdeleteʣ
  8. αϙʔτ͍ͯ͠ͳ͍ػೳ • update • ߋ৽͸setͰे෼ͩͬͨͷͰ • τϥϯβΫγϣϯ • ࣮૷͕ෳࡶʹͳΓͦ͏ͩͬͨͷͰݟૹΓ •

    onSnapshot() • firestore-simpleͷΠϯελϯε಺ͷcollectionRefʹ͸ΞΫηεͰ͖ ΔͷͰɺ΍Ζ͏ͱࢥ͑͹ී௨ʹՄೳ • ͨͩ͠ObjectΛฦ͞ͳ͍ͷͰૉͷFirestoreͱಉ͡ڍಈ • কདྷࣗ෼͕࢖͏Մೳੑ͕͋ΔͷͰɺͦͷͱ͖ʹαϙʔτ͢Δ͔΋ʁ