Skip to content

Commit 6d38423

Browse files
authored
refactor: remove public API constructors for Firebase services (#120)
* docs: update documentation link for sending messages to topic conditions * refactor: update constructors to use internal factory methods for AppCheck, Auth, Firestore, Messaging, and SecurityRules * update README
1 parent b6bd399 commit 6d38423

28 files changed

+224
-264
lines changed

packages/dart_firebase_admin/README.md

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ class:
5353
final app = FirebaseApp.initializeApp();
5454
```
5555

56-
This will automatically initalize the SDK with [Google Application Default Credentials](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application). Because default credentials lookup is fully automated in Google environments, with no need to supply environment variables or other configuration, this way of initializing the SDK is strongly recommended for applications running in Google environments such as Firebase App Hosting, Cloud Run, App Engine, and Cloud Functions for Firebase.
56+
This will automatically initialize the SDK with [Google Application Default Credentials](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application). Because default credentials lookup is fully automated in Google environments, with no need to supply environment variables or other configuration, this way of initializing the SDK is strongly recommended for applications running in Google environments such as Firebase App Hosting, Cloud Run, App Engine, and Cloud Functions for Firebase.
5757

5858
### Initialize the SDK in non-Google environments
5959

@@ -81,19 +81,19 @@ Once you have initialized an app instance with a credential, you can use any of
8181
final app = FirebaseApp.initializeApp();
8282
8383
// Getting a user by id
84-
final user = await app.auth.getUser("<user-id>");
84+
final user = await app.auth().getUser("<user-id>");
8585
8686
// Deleting a user by id
87-
await app.auth.deleteUser("<user-id>");
87+
await app.auth().deleteUser("<user-id>");
8888
8989
// Listing users
90-
final result = await app.auth.listUsers(maxResults: 10, pageToken: null);
90+
final result = await app.auth().listUsers(maxResults: 10, pageToken: null);
9191
final users = result.users;
9292
final nextPageToken = result.pageToken;
9393
9494
// Verifying an ID token (e.g. from request headers) from a client application
9595
final idToken = req.headers['Authorization'].split(' ')[1];
96-
final decodedToken = await app.auth.verifyIdToken(idToken, checkRevoked: true);
96+
final decodedToken = await app.auth().verifyIdToken(idToken, checkRevoked: true);
9797
final userId = decodedToken.uid;
9898
```
9999

@@ -103,11 +103,11 @@ final userId = decodedToken.uid;
103103
final app = FirebaseApp.initializeApp();
104104
105105
// Verifying an app check token
106-
final response = await app.appCheck.verifyToken("<appCheckToken>");
106+
final response = await app.appCheck().verifyToken("<appCheckToken>");
107107
print("App ID: ${response.appId}");
108108
109109
// Creating a new app check token
110-
final result = await app.appCheck.createToken("<app-id>");
110+
final result = await app.appCheck().createToken("<app-id>");
111111
print("Token: ${result.token}");
112112
```
113113

@@ -117,20 +117,20 @@ print("Token: ${result.token}");
117117
final app = FirebaseApp.initializeApp();
118118
119119
// Getting a document
120-
final snapshot = await app.firestore.collection("users").doc("<user-id>").get();
120+
final snapshot = await app.firestore().collection("users").doc("<user-id>").get();
121121
print(snapshot.data());
122122
123123
// Querying a collection
124-
final snapshot = await app.firestore.collection("users")
124+
final snapshot = await app.firestore().collection("users")
125125
.where('age', .greaterThan, 18)
126126
.orderBy('age', descending: true)
127127
.get();
128128
print(snapshot.docs())
129129
130130
// Running a transaction (e.g. adding credits to a balance)
131-
final balance = await app.firestore.runTransaction((tsx) async {
131+
final balance = await app.firestore().runTransaction((tsx) async {
132132
// Get a reference to a user document
133-
final ref = app.firestore.collection("users").doc("<user-id>");
133+
final ref = app.firestore().collection("users").doc("<user-id>");
134134
135135
// Get the document data
136136
final snapshot = await tsx.get(ref);
@@ -156,7 +156,7 @@ final balance = await app.firestore.runTransaction((tsx) async {
156156
final app = FirebaseApp.initializeApp();
157157
158158
// Get a task queue by name
159-
final queue = app.functions.taskQueue("<task-name>");
159+
final queue = app.functions().taskQueue("<task-name>");
160160
161161
// Add data to the queue
162162
await queue.enqueue({ "hello": "world" });
@@ -168,7 +168,7 @@ await queue.enqueue({ "hello": "world" });
168168
final app = FirebaseApp.initializeApp();
169169
170170
// Send a message to a specific device
171-
await app.messaging.send(
171+
await app.messaging().send(
172172
TokenMessage(
173173
token: "<device-token>",
174174
data: { "hello": "world" },
@@ -177,7 +177,7 @@ await app.messaging.send(
177177
);
178178
179179
// Send a message to a topic
180-
await app.messaging.send(
180+
await app.messaging().send(
181181
TopicMessage(
182182
topic: "<topic-name>",
183183
data: { "hello": "world" },
@@ -186,7 +186,7 @@ await app.messaging.send(
186186
);
187187
188188
// Send a message to a conditional statement
189-
await app.messaging.send(
189+
await app.messaging().send(
190190
ConditionMessage(
191191
condition: "\'stock-GOOG\' in topics || \'industry-tech\' in topics",
192192
data: { "hello": "world" },

packages/dart_firebase_admin/example/lib/main.dart

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import 'package:dart_firebase_admin/auth.dart';
22
import 'package:dart_firebase_admin/dart_firebase_admin.dart';
3-
import 'package:dart_firebase_admin/firestore.dart';
43
import 'package:dart_firebase_admin/functions.dart';
54
import 'package:dart_firebase_admin/messaging.dart';
65

@@ -32,7 +31,7 @@ Future<void> main() async {
3231
Future<void> authExample(FirebaseApp admin) async {
3332
print('\n### Auth Example ###\n');
3433

35-
final auth = Auth(admin);
34+
final auth = admin.auth();
3635

3736
UserRecord? user;
3837
try {
@@ -62,7 +61,7 @@ Future<void> authExample(FirebaseApp admin) async {
6261
Future<void> firestoreExample(FirebaseApp admin) async {
6362
print('\n### Firestore Example ###\n');
6463

65-
final firestore = Firestore(admin);
64+
final firestore = admin.firestore();
6665

6766
try {
6867
final collection = firestore.collection('users');
@@ -80,8 +79,7 @@ Future<void> firestoreExample(FirebaseApp admin) async {
8079
Future<void> projectConfigExample(FirebaseApp admin) async {
8180
print('\n### Project Config Example ###\n');
8281

83-
final auth = Auth(admin);
84-
final projectConfigManager = auth.projectConfigManager;
82+
final projectConfigManager = admin.auth().projectConfigManager;
8583

8684
try {
8785
// Get current project configuration
@@ -156,8 +154,7 @@ Future<void> projectConfigExample(FirebaseApp admin) async {
156154
Future<void> tenantExample(FirebaseApp admin) async {
157155
print('\n### Tenant Example ###\n');
158156

159-
final auth = Auth(admin);
160-
final tenantManager = auth.tenantManager;
157+
final tenantManager = admin.auth().tenantManager;
161158

162159
String? createdTenantId;
163160

@@ -246,7 +243,7 @@ Future<void> tenantExample(FirebaseApp admin) async {
246243
Future<void> messagingExample(FirebaseApp admin) async {
247244
print('\n### Messaging Example ###\n');
248245

249-
final messaging = Messaging(admin);
246+
final messaging = admin.messaging();
250247

251248
// Example 1: Send a message to a topic
252249
try {
@@ -402,7 +399,7 @@ Future<void> messagingExample(FirebaseApp admin) async {
402399
Future<void> functionsExample(FirebaseApp admin) async {
403400
print('\n### Functions Example ###\n');
404401

405-
final functions = Functions(admin);
402+
final functions = admin.functions();
406403

407404
// Get a task queue reference
408405
// The function name should match an existing Cloud Function or queue name

packages/dart_firebase_admin/example_server_app/pubspec.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ dependencies:
99
git:
1010
url: https://github.com/invertase/dart_firebase_admin.git
1111
path: packages/dart_firebase_admin
12-
ref: messaging/apis
12+
ref: next
1313
shelf: ^1.4.2
1414
shelf_router: ^1.1.2
1515

@@ -18,7 +18,7 @@ dependency_overrides:
1818
git:
1919
url: https://github.com/invertase/dart_firebase_admin.git
2020
path: packages/googleapis_auth_utils
21-
ref: messaging/apis
21+
ref: next
2222

2323
dev_dependencies:
2424
http: ^1.2.2

packages/dart_firebase_admin/lib/src/app/firebase_app.dart

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -151,42 +151,42 @@ class FirebaseApp {
151151
/// Gets the App Check service instance for this app.
152152
///
153153
/// Returns a cached instance if one exists, otherwise creates a new one.
154-
AppCheck get appCheck =>
155-
getOrInitService(FirebaseServiceType.appCheck.name, AppCheck.new);
154+
AppCheck appCheck() =>
155+
getOrInitService(FirebaseServiceType.appCheck.name, AppCheck.internal);
156156

157157
/// Gets the Auth service instance for this app.
158158
///
159159
/// Returns a cached instance if one exists, otherwise creates a new one.
160-
Auth get auth => getOrInitService(FirebaseServiceType.auth.name, Auth.new);
160+
Auth auth() => getOrInitService(FirebaseServiceType.auth.name, Auth.internal);
161161

162162
/// Gets the Firestore service instance for this app.
163163
///
164164
/// Returns a cached instance if one exists, otherwise creates a new one.
165165
/// Optional [settings] are only applied when creating a new instance.
166166
Firestore firestore({Settings? settings}) => getOrInitService(
167167
FirebaseServiceType.firestore.name,
168-
(app) => Firestore(app, settings: settings),
168+
(app) => Firestore.internal(app, settings: settings),
169169
);
170170

171171
/// Gets the Messaging service instance for this app.
172172
///
173173
/// Returns a cached instance if one exists, otherwise creates a new one.
174-
Messaging get messaging =>
175-
getOrInitService(FirebaseServiceType.messaging.name, Messaging.new);
174+
Messaging messaging() =>
175+
getOrInitService(FirebaseServiceType.messaging.name, Messaging.internal);
176176

177177
/// Gets the Security Rules service instance for this app.
178178
///
179179
/// Returns a cached instance if one exists, otherwise creates a new one.
180-
SecurityRules get securityRules => getOrInitService(
180+
SecurityRules securityRules() => getOrInitService(
181181
FirebaseServiceType.securityRules.name,
182-
SecurityRules.new,
182+
SecurityRules.internal,
183183
);
184184

185185
/// Gets the Functions service instance for this app.
186186
///
187187
/// Returns a cached instance if one exists, otherwise creates a new one.
188-
Functions get functions =>
189-
getOrInitService(FirebaseServiceType.functions.name, Functions.new);
188+
Functions functions() =>
189+
getOrInitService(FirebaseServiceType.functions.name, Functions.internal);
190190

191191
/// Closes this app and cleans up all associated resources.
192192
///

packages/dart_firebase_admin/lib/src/app_check/app_check.dart

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,6 @@ part 'app_check_request_handler.dart';
1919

2020
class AppCheck implements FirebaseService {
2121
/// Creates or returns the cached AppCheck instance for the given app.
22-
factory AppCheck(FirebaseApp app) {
23-
return app.getOrInitService(FirebaseServiceType.appCheck.name, AppCheck._);
24-
}
25-
26-
AppCheck._(this.app)
27-
: _requestHandler = AppCheckRequestHandler(app),
28-
_tokenGenerator = AppCheckTokenGenerator(app.createCryptoSigner()),
29-
_appCheckTokenVerifier = AppCheckTokenVerifier(app);
30-
3122
@internal
3223
factory AppCheck.internal(
3324
FirebaseApp app, {
@@ -37,7 +28,7 @@ class AppCheck implements FirebaseService {
3728
}) {
3829
return app.getOrInitService(
3930
FirebaseServiceType.appCheck.name,
40-
(app) => AppCheck._internal(
31+
(app) => AppCheck._(
4132
app,
4233
requestHandler: requestHandler,
4334
tokenGenerator: tokenGenerator,
@@ -46,7 +37,7 @@ class AppCheck implements FirebaseService {
4637
);
4738
}
4839

49-
AppCheck._internal(
40+
AppCheck._(
5041
this.app, {
5142
AppCheckRequestHandler? requestHandler,
5243
AppCheckTokenGenerator? tokenGenerator,

packages/dart_firebase_admin/lib/src/auth/auth.dart

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,6 @@ part of '../auth.dart';
44
/// An Auth instance can have multiple tenants.
55
class Auth extends _BaseAuth implements FirebaseService {
66
/// Creates or returns the cached Auth instance for the given app.
7-
factory Auth(FirebaseApp app) {
8-
return app.getOrInitService(FirebaseServiceType.auth.name, Auth._);
9-
}
10-
11-
Auth._(FirebaseApp app)
12-
: super(app: app, authRequestHandler: AuthRequestHandler(app));
13-
147
@internal
158
factory Auth.internal(
169
FirebaseApp app, {
@@ -20,7 +13,7 @@ class Auth extends _BaseAuth implements FirebaseService {
2013
}) {
2114
return app.getOrInitService(
2215
FirebaseServiceType.auth.name,
23-
(app) => Auth._internal(
16+
(app) => Auth._(
2417
app,
2518
requestHandler: requestHandler,
2619
idTokenVerifier: idTokenVerifier,
@@ -29,7 +22,7 @@ class Auth extends _BaseAuth implements FirebaseService {
2922
);
3023
}
3124

32-
Auth._internal(
25+
Auth._(
3326
FirebaseApp app, {
3427
AuthRequestHandler? requestHandler,
3528
super.idTokenVerifier,

packages/dart_firebase_admin/lib/src/functions/functions.dart

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,28 +27,19 @@ const _emulatedServiceAccountDefault = 'emulated-service-acct@email.com';
2727
/// those tasks before they execute.
2828
class Functions implements FirebaseService {
2929
/// Creates or returns the cached Functions instance for the given app.
30-
factory Functions(FirebaseApp app) {
31-
return app.getOrInitService(
32-
FirebaseServiceType.functions.name,
33-
Functions._,
34-
);
35-
}
36-
37-
/// An interface for interacting with Cloud Functions Task Queues.
38-
Functions._(this.app) : _requestHandler = FunctionsRequestHandler(app);
39-
4030
@internal
4131
factory Functions.internal(
4232
FirebaseApp app, {
4333
FunctionsRequestHandler? requestHandler,
4434
}) {
4535
return app.getOrInitService(
4636
FirebaseServiceType.functions.name,
47-
(app) => Functions._internal(app, requestHandler: requestHandler),
37+
(app) => Functions._(app, requestHandler: requestHandler),
4838
);
4939
}
5040

51-
Functions._internal(this.app, {FunctionsRequestHandler? requestHandler})
41+
/// An interface for interacting with Cloud Functions Task Queues.
42+
Functions._(this.app, {FunctionsRequestHandler? requestHandler})
5243
: _requestHandler = requestHandler ?? FunctionsRequestHandler(app);
5344

5445
/// The app associated with this Functions instance.

packages/dart_firebase_admin/lib/src/google_cloud_firestore/firestore.dart

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ class Firestore implements FirebaseService {
4141
///
4242
/// Note: Settings can only be specified on the first call. Subsequent calls
4343
/// will return the cached instance and ignore any new settings.
44-
factory Firestore(FirebaseApp app, {Settings? settings}) {
44+
@internal
45+
factory Firestore.internal(FirebaseApp app, {Settings? settings}) {
4546
return app.getOrInitService(
4647
FirebaseServiceType.firestore.name,
4748
(app) => Firestore._(app, settings: settings),

packages/dart_firebase_admin/lib/src/messaging/messaging.dart

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,32 +19,20 @@ const _fmcMaxBatchSize = 500;
1919
/// An interface for interacting with the Firebase Cloud Messaging service.
2020
class Messaging implements FirebaseService {
2121
/// Creates or returns the cached Messaging instance for the given app.
22-
factory Messaging(FirebaseApp app) {
23-
return app.getOrInitService(
24-
FirebaseServiceType.messaging.name,
25-
Messaging._,
26-
);
27-
}
28-
29-
/// An interface for interacting with the Firebase Cloud Messaging service.
30-
Messaging._(this.app)
31-
: _requestHandler = FirebaseMessagingRequestHandler(app);
32-
3322
@internal
3423
factory Messaging.internal(
3524
FirebaseApp app, {
3625
FirebaseMessagingRequestHandler? requestHandler,
3726
}) {
3827
return app.getOrInitService(
3928
FirebaseServiceType.messaging.name,
40-
(app) => Messaging._internal(app, requestHandler: requestHandler),
29+
(app) => Messaging._(app, requestHandler: requestHandler),
4130
);
4231
}
4332

44-
Messaging._internal(
45-
this.app, {
46-
FirebaseMessagingRequestHandler? requestHandler,
47-
}) : _requestHandler = requestHandler ?? FirebaseMessagingRequestHandler(app);
33+
/// An interface for interacting with the Firebase Cloud Messaging service.
34+
Messaging._(this.app, {FirebaseMessagingRequestHandler? requestHandler})
35+
: _requestHandler = requestHandler ?? FirebaseMessagingRequestHandler(app);
4836

4937
/// The app associated with this Messaging instance.
5038
@override

packages/dart_firebase_admin/lib/src/messaging/messaging_api.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ class TopicMessage extends Message {
101101

102102
/// A message targeting a condition.
103103
///
104-
/// See [Send messages to topics](https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-topics).
104+
/// See [Send to topic conditions](https://firebase.google.com/docs/cloud-messaging/send-topic-messages).
105105
class ConditionMessage extends Message {
106106
ConditionMessage({
107107
required this.condition,

0 commit comments

Comments
 (0)