-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfirestore_client.dart
More file actions
206 lines (179 loc) · 5.98 KB
/
firestore_client.dart
File metadata and controls
206 lines (179 loc) · 5.98 KB
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
// Copyright 2026 Firebase
//
// 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.
import 'dart:convert';
import 'test_client_base.dart';
/// Helper client for interacting with Firestore emulator REST API.
final class FirestoreClient extends TestClientBase {
FirestoreClient(super.baseUrl);
/// Creates a document with the specified ID.
///
/// Accepts a plain Dart map and automatically converts it to Firestore format.
///
/// Example:
/// ```dart
/// await client.createDocument('users', 'user123', {
/// 'name': 'John Doe',
/// 'age': 28,
/// 'tags': ['admin', 'premium'],
/// });
/// ```
Future<Map<String, dynamic>> createDocument(
String collectionPath,
String documentId,
Map<String, dynamic> data,
) async {
final url = '$baseUrl/$collectionPath?documentId=$documentId';
final response = await client.post(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'fields': fields(data)}),
);
if (response.statusCode != 200) {
throw Exception(
'Failed to create document: ${response.statusCode} ${response.body}',
);
}
return jsonDecode(response.body) as Map<String, dynamic>;
}
/// Updates a document using PATCH.
///
/// Accepts a plain Dart map and automatically converts it to Firestore format.
///
/// Example:
/// ```dart
/// await client.updateDocument('users/user123', {
/// 'name': 'Jane Smith',
/// 'age': 29,
/// });
/// ```
Future<Map<String, dynamic>> updateDocument(
String documentPath,
Map<String, dynamic> data,
) async {
final url = '$baseUrl/$documentPath';
final response = await client.patch(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'fields': fields(data)}),
);
if (response.statusCode != 200) {
throw Exception(
'Failed to update document: ${response.statusCode} ${response.body}',
);
}
return jsonDecode(response.body) as Map<String, dynamic>;
}
/// Deletes a document.
Future<void> deleteDocument(String documentPath) async {
final url = '$baseUrl/$documentPath';
final response = await client.delete(Uri.parse(url));
if (response.statusCode != 200) {
throw Exception(
'Failed to delete document: ${response.statusCode} ${response.body}',
);
}
}
/// Gets a document.
Future<Map<String, dynamic>?> getDocument(String documentPath) async {
final url = '$baseUrl/$documentPath';
final response = await client.get(Uri.parse(url));
if (response.statusCode == 404) {
return null;
}
if (response.statusCode != 200) {
throw Exception(
'Failed to get document: ${response.statusCode} ${response.body}',
);
}
return jsonDecode(response.body) as Map<String, dynamic>;
}
/// Helper to create a string field value.
static Map<String, dynamic> stringValue(String value) => {
'stringValue': value,
};
/// Helper to create an integer field value.
static Map<String, dynamic> intValue(int value) => {
'integerValue': value.toString(),
};
/// Helper to create a double field value.
static Map<String, dynamic> doubleValue(double value) => {
'doubleValue': value,
};
/// Helper to create a boolean field value.
static Map<String, dynamic> boolValue({required bool value}) => {
'booleanValue': value,
};
/// Helper to create a null field value.
static Map<String, dynamic> nullValue() => {'nullValue': null};
/// Helper to create a map field value.
static Map<String, dynamic> mapValue(Map<String, dynamic> fields) => {
'mapValue': {'fields': fields},
};
/// Helper to create an array field value.
static Map<String, dynamic> arrayValue(List<Map<String, dynamic>> values) => {
'arrayValue': {'values': values},
};
/// Automatically converts a Dart value to Firestore field format.
///
/// Supports:
/// - String, int, double, bool, null
/// - Lists (converted to arrayValue)
/// - Maps (converted to mapValue with nested fields)
///
/// Example:
/// ```dart
/// value('hello') // {'stringValue': 'hello'}
/// value(42) // {'integerValue': '42'}
/// value([1, 2]) // {'arrayValue': {'values': [...]}}
/// value({'key': 'value'}) // {'mapValue': {'fields': {...}}}
/// ```
static Map<String, dynamic> value(dynamic val) {
if (val is String) return stringValue(val);
if (val is int) return intValue(val);
if (val is double) return doubleValue(val);
if (val is bool) return boolValue(value: val);
if (val == null) return nullValue();
if (val is List) {
return arrayValue(val.map((e) => value(e)).toList());
}
if (val is Map) {
final firestoreFields = <String, dynamic>{};
for (final entry in val.entries) {
firestoreFields[entry.key.toString()] = value(entry.value);
}
return mapValue(firestoreFields);
}
throw ArgumentError('Unsupported type: ${val.runtimeType}');
}
/// Converts a map of Dart values to Firestore fields format.
///
/// This is a convenience method for converting an entire document's fields.
///
/// Example:
/// ```dart
/// fields({
/// 'name': 'John Doe',
/// 'age': 28,
/// 'active': true,
/// 'tags': ['admin', 'premium'],
/// })
/// ```
static Map<String, dynamic> fields(Map<String, dynamic> data) {
final result = <String, dynamic>{};
for (final entry in data.entries) {
result[entry.key] = value(entry.value);
}
return result;
}
}