/
CollectionReference.java
222 lines (203 loc) · 7.81 KB
/
CollectionReference.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.firestore;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.InternalExtensionOnly;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptions;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.firestore.spi.v1.FirestoreRpc;
import com.google.cloud.firestore.v1.FirestoreClient.ListDocumentsPagedResponse;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.firestore.v1.Document;
import com.google.firestore.v1.DocumentMask;
import com.google.firestore.v1.ListDocumentsRequest;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A CollectionReference can be used for adding documents, getting document references, and querying
* for documents (using the methods inherited from Query).
*
* <p><b>Subclassing Note</b>: Firestore classes are not meant to be subclassed except for use in
* test mocks. Subclassing is not supported in production code and new SDK releases may break code
* that does so.
*/
@InternalExtensionOnly
public class CollectionReference extends Query {
/**
* Creates a CollectionReference from a complete collection path.
*
* @param rpcContext The Firestore client.
* @param collectionPath The Path of this collection.
*/
CollectionReference(FirestoreRpcContext<?> rpcContext, ResourcePath collectionPath) {
super(rpcContext, collectionPath);
}
/**
* The id of a collection refers to the last component of path pointing to a collection, e.g.
* "collection-id" in "projects/project-id/databases/database-id/documents/collection-id".
*
* @return The ID of the collection.
*/
@Nonnull
public String getId() {
return options.getCollectionId();
}
/**
* Returns a DocumentReference to the containing Document if this is a subcollection, else null.
*
* @return A DocumentReference pointing to the parent document.
*/
@Nullable
public DocumentReference getParent() {
ResourcePath parent = options.getParentPath();
return parent.isDocument() ? new DocumentReference(rpcContext, parent) : null;
}
/**
* A string representing the path of the referenced collection (relative to the root of the
* database).
*
* @return The slash-separated path relative to the root of the database.
*/
@Nonnull
public String getPath() {
return getResourcePath().getPath();
}
/**
* Returns a DocumentReference pointing to a new document with an auto-generated ID within this
* collection.
*
* @return A DocumentReference pointing to a new document with an auto-generated ID.
*/
@Nonnull
public DocumentReference document() {
return document(FirestoreImpl.autoId());
}
/**
* Gets a DocumentReference instance that refers to the document that is a child of this
* Collection.
*
* @param childPath A relative and slash-separated path to a document.
* @return The DocumentReference instance.
*/
@Nonnull
public DocumentReference document(@Nonnull String childPath) {
ResourcePath documentPath = getResourcePath().append(childPath);
Preconditions.checkArgument(
documentPath.isDocument(),
String.format("Path should point to a Document Reference: %s", getPath()));
return new DocumentReference(rpcContext, documentPath);
}
/**
* Retrieves the list of documents in this collection.
*
* <p>The document references returned may include references to "missing documents", i.e.
* document locations that have no document present but which contain subcollections with
* documents. Attempting to read such a document reference (e.g. via `get()` or `onSnapshot()`)
* will return a `DocumentSnapshot` whose `exists()` method returns false.
*
* @return The list of documents in this collection.
*/
@Nonnull
public Iterable<DocumentReference> listDocuments() {
ListDocumentsRequest.Builder request = ListDocumentsRequest.newBuilder();
request.setParent(options.getParentPath().toString());
request.setCollectionId(options.getCollectionId());
request.setMask(DocumentMask.getDefaultInstance());
request.setShowMissing(true);
final ListDocumentsPagedResponse response;
try {
FirestoreRpc client = rpcContext.getClient();
UnaryCallable<ListDocumentsRequest, ListDocumentsPagedResponse> callable =
client.listDocumentsPagedCallable();
ListDocumentsRequest build = request.build();
ApiFuture<ListDocumentsPagedResponse> future = rpcContext.sendRequest(build, callable);
response = ApiExceptions.callAndTranslateApiException(future);
} catch (ApiException exception) {
throw FirestoreException.apiException(exception);
}
return new Iterable<DocumentReference>() {
@Override
@Nonnull
public Iterator<DocumentReference> iterator() {
final Iterator<Document> iterator = response.iterateAll().iterator();
return new Iterator<DocumentReference>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public DocumentReference next() {
ResourcePath path = ResourcePath.create(iterator.next().getName());
return document(path.getId());
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
};
}
/**
* Adds a new document to this collection with the specified data, assigning it a document ID
* automatically.
*
* @param fields A Map containing the data for the new document.
* @return An ApiFuture that will be resolved with the DocumentReference of the newly created
* document.
* @see #document()
*/
@Nonnull
public ApiFuture<DocumentReference> add(@Nonnull final Map<String, Object> fields) {
final DocumentReference documentReference = document();
ApiFuture<WriteResult> createFuture = documentReference.create(fields);
return ApiFutures.transform(
createFuture,
new ApiFunction<WriteResult, DocumentReference>() {
@Override
public DocumentReference apply(WriteResult writeResult) {
return documentReference;
}
},
MoreExecutors.directExecutor());
}
/**
* Adds a new document to this collection with the specified POJO as contents, assigning it a
* document ID automatically.
*
* @param pojo The POJO that will be used to populate the contents of the document
* @return An ApiFuture that will be resolved with the DocumentReference of the newly created
* document.
* @see #document()
*/
public ApiFuture<DocumentReference> add(Object pojo) {
Object converted = CustomClassMapper.convertToPlainJavaTypes(pojo);
if (!(converted instanceof Map)) {
throw FirestoreException.invalidState("Can't set a document's data to an array or primitive");
}
return add((Map<String, Object>) converted);
}
/** Returns a resource path pointing to this collection. */
ResourcePath getResourcePath() {
return options.getParentPath().append(options.getCollectionId());
}
}