From 122b612741884e4c8d1dfc2956972f3f5e06b4da Mon Sep 17 00:00:00 2001 From: shoNagai Date: Sat, 8 May 2021 10:34:25 +0900 Subject: [PATCH 1/2] =?UTF-8?q?docs:=20=E2=9C=8F=EF=B8=8F=20Add=20example?= =?UTF-8?q?=20for=20Cloud=20Firestore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/CloudFirestore.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 examples/CloudFirestore.md diff --git a/examples/CloudFirestore.md b/examples/CloudFirestore.md new file mode 100644 index 0000000..84db2b7 --- /dev/null +++ b/examples/CloudFirestore.md @@ -0,0 +1,29 @@ +# Using DataLoader with Cloud Firestore + +Cloud Firestore is a "NoSQL" document-oriented database which supports [in operator](https://firebase.google.com/docs/firestore/query-data/queries#in_not-in_and_array-contains-any), +making it can be used with DataLoader. + +Here we build an example Cloud Firestore DataLoader using [firebase-admin](https://firebase.google.com/docs/admin/setup?hl=en). + +```js +const admin = require("firebase-admin"); + +admin.initializeApp({ + // You need to Initialize the SDK +}); + +const datastoreLoader = new DataLoader( + async (keys) => { + const snapshot = await admin + .firestore() + .collection(`users`) + .where(admin.firestore.FieldPath.documentId(), `in`, keys) + .get(); + return snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })); + }, + { + // The in clause of Cloud Firestore is support up to 10 comparison values + maxBatchSize: 10, + } +); +``` From d8ba705d1f830f48f0a2d765948c9c37290e6b2e Mon Sep 17 00:00:00 2001 From: shoNagai Date: Sat, 15 May 2021 11:47:43 +0900 Subject: [PATCH 2/2] =?UTF-8?q?docs:=20=E2=9C=8F=EF=B8=8F=20add=20sorted?= =?UTF-8?q?=20by=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/CloudFirestore.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/CloudFirestore.md b/examples/CloudFirestore.md index 84db2b7..9697313 100644 --- a/examples/CloudFirestore.md +++ b/examples/CloudFirestore.md @@ -19,7 +19,12 @@ const datastoreLoader = new DataLoader( .collection(`users`) .where(admin.firestore.FieldPath.documentId(), `in`, keys) .get(); - return snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })); + // By default, a query retrieves all documents that satisfy the query in ascending order by document ID. + // Therefore, it is recommended to sort by key + return keys.map((key) => { + const doc = snapshot.docs.find((doc) => doc.id === key); + return doc ? { ...doc.data(), id: doc.id } : null; + }); }, { // The in clause of Cloud Firestore is support up to 10 comparison values