Skip to content

Commit 7d9a193

Browse files
feat(firestore): add get method for collection
1 parent 2f8c397 commit 7d9a193

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

firebase/firestore/__init__.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@ def __init__(self, collection_path, api_key, credentials, project_id, requests):
9090
self._project_id = project_id
9191
self._requests = requests
9292

93+
self._base_path = f"projects/{self._project_id}/databases/(default)/documents"
94+
self._base_url = f"https://firestore.googleapis.com/v1/{self._base_path}"
95+
96+
if self._credentials:
97+
self.__datastore = Client(credentials=self._credentials, project=self._project_id)
98+
9399
def document(self, document_id):
94100
""" A reference to a document in a collection.
95101
@@ -105,6 +111,52 @@ def document(self, document_id):
105111
self._path.append(document_id)
106112
return Document(self._path, api_key=self._api_key, credentials=self._credentials, project_id=self._project_id, requests=self._requests)
107113

114+
def get(self, token=None):
115+
""" Returns a list of dict's containing document ID and the
116+
data stored within them.
117+
118+
119+
:type token: str
120+
:param token: (Optional) Firebase Auth User ID Token, defaults
121+
to :data:`None`.
122+
123+
124+
:return: A list of document ID's with the data they possess.
125+
:rtype: list
126+
"""
127+
128+
path = self._path.copy()
129+
self._path.clear()
130+
131+
docs = []
132+
133+
if self._credentials:
134+
db_ref = _build_db(self.__datastore, path)
135+
136+
results = db_ref.get()
137+
138+
for result in results:
139+
docs.append({result.id: result.to_dict()})
140+
141+
else:
142+
143+
req_ref = f"{self._base_url}/{'/'.join(path)}?key={self._api_key}"
144+
145+
if token:
146+
headers = {"Authorization": "Firebase " + token}
147+
response = self._requests.get(req_ref, headers=headers)
148+
149+
else:
150+
response = self._requests.get(req_ref)
151+
152+
raise_detailed_error(response)
153+
154+
for doc in response.json()['documents']:
155+
doc_id = doc['name'].split('/')
156+
docs.append({doc_id.pop(): _from_datastore({'fields': doc['fields']})})
157+
158+
return docs
159+
108160

109161
class Document:
110162
""" A reference to a document in a Firestore database.

0 commit comments

Comments
 (0)