Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example for Cloud Firestore #268

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions 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 }));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does firestore guarantee the results will be in the same order as the keys input? If you're not sure this is the case, I think it might be safer if this line was something like:

Suggested change
return snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
return keys.map(key => {
const doc = snapshot.docs.find(doc => doc.id === key);
return doc ? { ...doc.data(), id: doc.id } : null;
});

(Obviously test this works before adopting it; I've never used Firestore.)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@benjie
Thank you for your review.

As you said, firestore is retrieved in ascending order by document ID by default, so I think sorting by input key is necessary.

I have added the correction and comments.

I have also implemented and confirmed the test in my repository.

},
{
// The in clause of Cloud Firestore is support up to 10 comparison values
maxBatchSize: 10,
}
);
```