-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.dart
More file actions
775 lines (683 loc) · 27.3 KB
/
main.dart
File metadata and controls
775 lines (683 loc) · 27.3 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
import 'dart:convert';
import 'dart:io';
import 'package:firebase_functions/firebase_functions.dart';
// =============================================================================
// Parameterized Configuration Examples
// =============================================================================
// Define parameters - these are read from environment variables at runtime
// and can be configured at deploy time via .env files or CLI prompts.
final welcomeMessage = defineString(
'WELCOME_MESSAGE',
ParamOptions(
defaultValue: 'Hello from Dart Functions!',
label: 'Welcome Message',
description: 'The greeting message returned by the helloWorld function',
),
);
final minInstances = defineInt(
'MIN_INSTANCES',
ParamOptions(
defaultValue: 0,
label: 'Minimum Instances',
description: 'Minimum number of instances to keep warm',
),
);
final isProduction = defineBoolean(
'IS_PRODUCTION',
ParamOptions(
defaultValue: false,
description: 'Whether this is a production deployment',
),
);
void main(List<String> args) async {
await fireUp(args, (firebase) {
// ==========================================================================
// HTTPS Callable Functions (onCall / onCallWithData)
// ==========================================================================
// Basic callable function - untyped data
firebase.https.onCall(name: 'greet', (request, response) async {
final data = request.data as Map<String, dynamic>?;
final name = data?['name'] ?? 'World';
return CallableResult({'message': 'Hello, $name!'});
});
// Callable function with typed data using fromJson
firebase.https.onCallWithData<GreetRequest, GreetResponse>(
name: 'greetTyped',
fromJson: GreetRequest.fromJson,
(request, response) async {
return GreetResponse(message: 'Hello, ${request.data.name}!');
},
);
// Callable function demonstrating error handling
firebase.https.onCall(name: 'divide', (request, response) async {
final data = request.data as Map<String, dynamic>?;
final a = (data?['a'] as num?)?.toDouble();
final b = (data?['b'] as num?)?.toDouble();
if (a == null || b == null) {
throw InvalidArgumentError('Both "a" and "b" are required');
}
if (b == 0) {
throw FailedPreconditionError('Cannot divide by zero');
}
return CallableResult({'result': a / b});
});
// Callable function demonstrating auth data extraction
firebase.https.onCall(name: 'getAuthInfo', (request, response) async {
final auth = request.auth;
if (auth == null) {
// User is not authenticated
return CallableResult({
'authenticated': false,
'message': 'No authentication provided',
});
}
// User is authenticated - return auth info
return CallableResult({
'authenticated': true,
'uid': auth.uid,
'token': auth.token, // Decoded JWT claims (email, name, etc.)
// Note: auth.rawToken contains the raw JWT string if needed
});
});
// Callable function with streaming support
firebase.https.onCall(
name: 'countdown',
options: const CallableOptions(
heartBeatIntervalSeconds: HeartBeatIntervalSeconds(5),
),
(request, response) async {
final data = request.data as Map<String, dynamic>?;
final start = (data?['start'] as num?)?.toInt() ?? 10;
// Stream countdown if client supports it
if (request.acceptsStreaming) {
for (var i = start; i >= 0; i--) {
await response.sendChunk({'count': i});
await Future<void>.delayed(const Duration(milliseconds: 100));
}
}
return CallableResult({'message': 'Countdown complete!'});
},
);
// ==========================================================================
// HTTPS onRequest Functions
// ==========================================================================
// HTTPS onRequest example - using parameterized configuration
firebase.https.onRequest(
name: 'helloWorld',
// ignore: non_const_argument_for_const_parameter
options: HttpsOptions(
// Use parameters in options - evaluated at deploy time
minInstances: DeployOption.param(minInstances),
),
(request) async {
// Access parameter value at runtime
return Response.ok(welcomeMessage.value());
},
);
// Conditional configuration based on boolean parameter
firebase.https.onRequest(
name: 'configuredEndpoint',
// ignore: non_const_argument_for_const_parameter
options: HttpsOptions(
// Use thenElse for conditional configuration at deploy time
// isProduction.thenElse(trueValue, falseValue) returns an expression
memory: Memory.expression(isProduction.thenElse(2048, 512)),
),
(request) async {
// Access parameter value at runtime
final env = isProduction.value() ? 'production' : 'development';
return Response.ok('Running in $env mode');
},
);
// Pub/Sub trigger example
firebase.pubsub.onMessagePublished(topic: 'my-topic', (event) async {
final message = event.data;
print('Received Pub/Sub message:');
print(' ID: ${message?.messageId}');
print(' Published: ${message?.publishTime}');
print(' Data: ${message?.textData}');
print(' Attributes: ${message?.attributes}');
});
// Firestore trigger examples
firebase.firestore.onDocumentCreated(document: 'users/{userId}', (
event,
) async {
final data = event.data?.data();
print('Document created: users/${event.params['userId']}');
print(' Name: ${data?['name']}');
print(' Email: ${data?['email']}');
});
firebase.firestore.onDocumentUpdated(document: 'users/{userId}', (
event,
) async {
final before = event.data?.before?.data();
final after = event.data?.after?.data();
print('Document updated: users/${event.params['userId']}');
print(' Before: $before');
print(' After: $after');
});
firebase.firestore.onDocumentDeleted(document: 'users/{userId}', (
event,
) async {
final data = event.data?.data();
print('Document deleted: users/${event.params['userId']}');
print(' Final data: $data');
// write result to Firestore so the e2e test can assert on
// what the handler actually received (exposes the old_value/value).
final userId = event.params['userId'] as String;
final firestoreHost =
Platform.environment['FIRESTORE_EMULATOR_HOST'] ?? '127.0.0.1:8080';
final parts = firestoreHost.split(':');
final host = parts[0];
final port = int.tryParse(parts.length > 1 ? parts[1] : '8080') ?? 8080;
final resultFields = <String, dynamic>{
'hasData': {'booleanValue': data != null},
'name': {'stringValue': data?['name']?.toString() ?? ''},
'email': {'stringValue': data?['email']?.toString() ?? ''},
'finalMessage': {
'stringValue': data?['finalMessage']?.toString() ?? '',
},
};
try {
final httpClient = HttpClient();
final req = await httpClient.post(
host,
port,
'/v1/projects/demo-test/databases/(default)/documents/'
'trigger_results?documentId=deleted_$userId',
);
req.headers.contentType = ContentType.json;
req.write(jsonEncode({'fields': resultFields}));
await req.close();
httpClient.close();
} catch (e) {
print(
' Firestore write to verify handler '
'received event.data failed: $e',
);
}
});
firebase.firestore.onDocumentWritten(document: 'users/{userId}', (
event,
) async {
final before = event.data?.before?.data();
final after = event.data?.after?.data();
print('Document written: users/${event.params['userId']}');
if (before == null && after != null) {
print(' Operation: CREATE');
} else if (before != null && after != null) {
print(' Operation: UPDATE');
} else if (before != null && after == null) {
print(' Operation: DELETE');
}
});
// Firestore WithAuthContext trigger examples
firebase.firestore.onDocumentCreatedWithAuthContext(
document: 'orders/{orderId}',
(event) async {
print('Document created by: ${event.authType} (${event.authId})');
final data = event.data?.data();
print(' Order: ${data?['product']}');
},
);
firebase.firestore.onDocumentUpdatedWithAuthContext(
document: 'orders/{orderId}',
(event) async {
print('Document updated by: ${event.authType} (${event.authId})');
},
);
firebase.firestore.onDocumentDeletedWithAuthContext(
document: 'orders/{orderId}',
(event) async {
print('Document deleted by: ${event.authType} (${event.authId})');
},
);
firebase.firestore.onDocumentWrittenWithAuthContext(
document: 'orders/{orderId}',
(event) async {
print('Document written by: ${event.authType} (${event.authId})');
},
);
// Nested collection trigger example
firebase.firestore.onDocumentCreated(
document: 'posts/{postId}/comments/{commentId}',
(event) async {
final data = event.data?.data();
print(
'Comment created: posts/${event.params['postId']}/comments/${event.params['commentId']}',
);
print(' Text: ${data?['text']}');
print(' Author: ${data?['author']}');
},
);
// ==========================================================================
// Realtime Database trigger examples
// ==========================================================================
// Database onValueCreated - triggers when data is created
firebase.database.onValueCreated(ref: 'messages/{messageId}', (
event,
) async {
final data = event.data?.val();
print('Database value created: messages/${event.params['messageId']}');
print(' Data: $data');
print(' Instance: ${event.instance}');
print(' Ref: ${event.ref}');
});
// Database onValueUpdated - triggers when data is updated
firebase.database.onValueUpdated(ref: 'messages/{messageId}', (
event,
) async {
final before = event.data?.before?.val();
final after = event.data?.after?.val();
print('Database value updated: messages/${event.params['messageId']}');
print(' Before: $before');
print(' After: $after');
});
// Database onValueDeleted - triggers when data is deleted
firebase.database.onValueDeleted(ref: 'messages/{messageId}', (
event,
) async {
final data = event.data?.val();
print('Database value deleted: messages/${event.params['messageId']}');
print(' Final data: $data');
});
// Database onValueWritten - triggers on any write (create, update, delete)
firebase.database.onValueWritten(ref: 'messages/{messageId}', (
event,
) async {
final before = event.data?.before;
final after = event.data?.after;
print('Database value written: messages/${event.params['messageId']}');
if (before == null || !before.exists()) {
print(' Operation: CREATE');
print(' New data: ${after?.val()}');
} else if (after == null || !after.exists()) {
print(' Operation: DELETE');
print(' Deleted data: ${before.val()}');
} else {
print(' Operation: UPDATE');
print(' Before: ${before.val()}');
print(' After: ${after.val()}');
}
});
// Nested path database trigger
firebase.database.onValueWritten(ref: 'users/{userId}/status', (
event,
) async {
final after = event.data?.after?.val();
print('User status changed: ${event.params['userId']}');
print(' New status: $after');
});
// ==========================================================================
// Firebase Alerts trigger examples
// ==========================================================================
// Crashlytics new fatal issue alert
firebase.alerts.crashlytics.onNewFatalIssuePublished((event) async {
final issue = event.data?.payload.issue;
print('New fatal issue in Crashlytics:');
print(' Issue ID: ${issue?.id}');
print(' Title: ${issue?.title}');
print(' App Version: ${issue?.appVersion}');
print(' App ID: ${event.appId}');
});
// Billing plan update alert
firebase.alerts.billing.onPlanUpdatePublished((event) async {
final payload = event.data?.payload;
print('Billing plan updated:');
print(' New Plan: ${payload?.billingPlan}');
print(' Updated By: ${payload?.principalEmail}');
print(' Type: ${payload?.notificationType}');
});
// Performance threshold alert with app ID filter
firebase.alerts.performance.onThresholdAlertPublished(
options: const AlertOptions(appId: '1:123456789:ios:abcdef'),
(event) async {
final payload = event.data?.payload;
print('Performance threshold exceeded:');
print(' Event: ${payload?.eventName}');
print(' Metric: ${payload?.metricType}');
print(
' Threshold: ${payload?.thresholdValue} ${payload?.thresholdUnit}',
);
print(' Actual: ${payload?.violationValue} ${payload?.violationUnit}');
},
);
// ==========================================================================
// Identity Platform (Auth Blocking) trigger examples
// ==========================================================================
// Before user created - runs before a new user is created
firebase.identity.beforeUserCreated(
options: const BlockingOptions(idToken: true, accessToken: true),
(AuthBlockingEvent event) async {
final user = event.data;
print('Before user created:');
print(' UID: ${user?.uid}');
print(' Email: ${user?.email}');
print(' Provider: ${event.additionalUserInfo?.providerId}');
// Example: Block users with certain email domains
final email = user?.email;
if (email != null && email.endsWith('@blocked.com')) {
throw PermissionDeniedError('Email domain not allowed');
}
// Example: Set custom claims based on email domain
if (email != null && email.endsWith('@admin.com')) {
return const BeforeCreateResponse(customClaims: {'admin': true});
}
return null;
},
);
// Before user signed in - runs before a user signs in
firebase.identity.beforeUserSignedIn(
options: const BlockingOptions(idToken: true),
(AuthBlockingEvent event) async {
final user = event.data;
print('Before user signed in:');
print(' UID: ${user?.uid}');
print(' Email: ${user?.email}');
print(' IP Address: ${event.ipAddress}');
// Example: Add session claims for tracking
return BeforeSignInResponse(
sessionClaims: {
'lastLogin': DateTime.now().toIso8601String(),
'signInIp': event.ipAddress,
},
);
},
);
// Before email sent - runs before password reset or sign-in emails
// NOTE: The Auth emulator only supports beforeCreate and beforeSignIn.
// This function is included for manifest snapshot testing but cannot be
// tested with the emulator.
firebase.identity.beforeEmailSent((AuthBlockingEvent event) async {
print('Before email sent:');
print(' Email Type: ${event.emailType?.value}');
print(' IP Address: ${event.ipAddress}');
// Example: Rate limit password reset emails
// In production, you'd check against a database
if (event.emailType == EmailType.passwordReset) {
// Could return BeforeEmailResponse(
// recaptchaActionOverride: RecaptchaActionOptions.block,
// ) to block suspicious requests
}
return null;
});
// Before SMS sent - runs before MFA or sign-in SMS messages
// NOTE: The Auth emulator only supports beforeCreate and beforeSignIn.
// This function is included for manifest snapshot testing but cannot be
// tested with the emulator.
firebase.identity.beforeSmsSent((AuthBlockingEvent event) async {
print('Before SMS sent:');
print(' SMS Type: ${event.smsType?.value}');
print(' Phone: ${event.additionalUserInfo?.phoneNumber}');
// Example: Block SMS to certain country codes
final phone = event.additionalUserInfo?.phoneNumber;
if (phone != null && phone.startsWith('+1900')) {
return const BeforeSmsResponse(
recaptchaActionOverride: RecaptchaActionOptions.block,
);
}
return null;
});
// ==========================================================================
// Remote Config trigger examples
// ==========================================================================
// Remote Config update trigger
firebase.remoteConfig.onConfigUpdated((event) async {
final data = event.data;
print('Remote Config updated:');
print(' Version: ${data?.versionNumber}');
print(' Description: ${data?.description}');
print(' Update Origin: ${data?.updateOrigin.value}');
print(' Update Type: ${data?.updateType.value}');
print(' Updated By: ${data?.updateUser.email}');
});
// ==========================================================================
// Cloud Storage trigger examples
// ==========================================================================
// Storage onObjectFinalized - triggers when an object is created/overwritten
firebase.storage.onObjectFinalized(
bucket: 'demo-test.firebasestorage.app',
(event) async {
final data = event.data;
print('Object finalized in bucket: ${event.bucket}');
print(' Name: ${data?.name}');
print(' Content Type: ${data?.contentType}');
print(' Size: ${data?.size}');
},
);
// Storage onObjectArchived - triggers when an object is archived
firebase.storage.onObjectArchived(bucket: 'demo-test.firebasestorage.app', (
event,
) async {
final data = event.data;
print('Object archived in bucket: ${event.bucket}');
print(' Name: ${data?.name}');
print(' Storage Class: ${data?.storageClass}');
});
// Storage onObjectDeleted - triggers when an object is deleted
firebase.storage.onObjectDeleted(bucket: 'demo-test.firebasestorage.app', (
event,
) async {
final data = event.data;
print('Object deleted in bucket: ${event.bucket}');
print(' Name: ${data?.name}');
});
// Storage onObjectMetadataUpdated - triggers when object metadata changes
firebase.storage.onObjectMetadataUpdated(
bucket: 'demo-test.firebasestorage.app',
(event) async {
final data = event.data;
print('Object metadata updated in bucket: ${event.bucket}');
print(' Name: ${data?.name}');
print(' Metadata: ${data?.metadata}');
},
);
// ==========================================================================
// Eventarc trigger examples
// ==========================================================================
// Basic Eventarc custom event - uses default Firebase channel
firebase.eventarc.onCustomEventPublished(eventType: 'com.example.myevent', (
event,
) async {
print('Received custom Eventarc event:');
print(' Type: ${event.type}');
print(' Source: ${event.source}');
print(' Data: ${event.data}');
});
// Eventarc custom event with channel and filters
firebase.eventarc.onCustomEventPublished(
eventType: 'com.example.filtered',
options: const EventarcTriggerOptions(
channel: 'my-channel',
filters: {'category': 'important'},
),
(event) async {
print('Received filtered Eventarc event:');
print(' Type: ${event.type}');
print(' Data: ${event.data}');
},
);
// ==========================================================================
// Scheduler trigger examples
// ==========================================================================
// Basic scheduled function - runs every day at midnight
firebase.scheduler.onSchedule(schedule: '0 0 * * *', (event) async {
print('Scheduled function triggered:');
print(' Job Name: ${event.jobName}');
print(' Schedule Time: ${event.scheduleTime}');
// Perform daily cleanup, send reports, etc.
});
// Scheduled function with timezone and retry config
firebase.scheduler.onSchedule(
schedule: '0 9 * * 1-5',
options: const ScheduleOptions(
timeZone: TimeZone('America/New_York'),
retryConfig: RetryConfig(
retryCount: RetryCount(3),
maxRetrySeconds: MaxRetrySeconds(60),
minBackoffSeconds: MinBackoffSeconds(5),
maxBackoffSeconds: MaxBackoffSeconds(30),
),
memory: Memory(MemoryOption.mb256),
),
(event) async {
print('Weekday morning report:');
print(' Executed at: ${event.scheduleDateTime}');
// Generate and send morning reports
},
);
// ==========================================================================
// Test Lab trigger examples
// ==========================================================================
// Test Lab onTestMatrixCompleted - triggers when a test matrix completes
firebase.testLab.onTestMatrixCompleted((event) async {
final data = event.data;
print('Test matrix completed:');
print(' Matrix ID: ${data?.testMatrixId}');
print(' State: ${data?.state.value}');
print(' Outcome: ${data?.outcomeSummary.value}');
print(' Client: ${data?.clientInfo.client}');
print(' Results URI: ${data?.resultStorage.resultsUri}');
});
// ==========================================================================
// Task Queue trigger examples
// ==========================================================================
// Basic task queue function
firebase.tasks.onTaskDispatched(name: 'processOrder', (request) async {
final data = request.data as Map<String, dynamic>;
print('Processing order: ${data['orderId']}');
print('Task ID: ${request.id}');
print('Queue: ${request.queueName}');
print('Retry count: ${request.retryCount}');
});
// Task queue function with options
firebase.tasks.onTaskDispatched(
name: 'sendEmail',
options: const TaskQueueOptions(
retryConfig: TaskQueueRetryConfig(
maxAttempts: MaxAttempts(5),
maxRetrySeconds: TaskMaxRetrySeconds(300),
minBackoffSeconds: TaskMinBackoffSeconds(10),
maxBackoffSeconds: TaskMaxBackoffSeconds(60),
maxDoublings: TaskMaxDoublings(3),
),
rateLimits: TaskQueueRateLimits(
maxConcurrentDispatches: MaxConcurrentDispatches(100),
maxDispatchesPerSecond: MaxDispatchesPerSecond(50),
),
memory: Memory(MemoryOption.mb512),
),
(request) async {
final data = request.data as Map<String, dynamic>;
print('Sending email to: ${data['to']}');
print('Subject: ${data['subject']}');
},
);
// ==========================================================================
// Options Tests - functions with comprehensive option configurations
// ==========================================================================
// HTTPS onRequest with ALL GlobalOptions + cors
firebase.https.onRequest(
name: 'httpsFull',
options: const HttpsOptions(
// GlobalOptions (manifest options)
memory: Memory(MemoryOption.mb512),
cpu: Cpu(1),
region: Region(SupportedRegion.usCentral1),
timeoutSeconds: TimeoutSeconds(60),
minInstances: Instances(0),
maxInstances: Instances(10),
concurrency: Concurrency(80),
serviceAccount: ServiceAccount('test@example.com'),
vpcConnector: VpcConnector(
'projects/test/locations/us-central1/connectors/vpc',
),
vpcConnectorEgressSettings: VpcConnectorEgressSettings(
VpcEgressSetting.privateRangesOnly,
),
ingressSettings: Ingress(IngressSetting.allowAll),
invoker: Invoker.public(),
labels: {'environment': 'test', 'team': 'backend'},
omit: Omit(false),
// Runtime-only options (NOT in manifest)
preserveExternalChanges: PreserveExternalChanges(true),
cors: Cors(['https://example.com', 'https://app.example.com']),
),
(request) async => Response.ok('HTTPS with all options'),
);
// Callable with ALL CallableOptions
firebase.https.onCall(
name: 'callableFull',
options: const CallableOptions(
memory: Memory(MemoryOption.gb1),
cpu: Cpu(2),
region: Region(SupportedRegion.usEast1),
timeoutSeconds: TimeoutSeconds(300),
minInstances: Instances(1),
maxInstances: Instances(100),
concurrency: Concurrency(80),
invoker: Invoker.private(),
labels: {'type': 'callable'},
// Runtime-only options (NOT in manifest)
enforceAppCheck: EnforceAppCheck(true),
consumeAppCheckToken: ConsumeAppCheckToken(true),
heartBeatIntervalSeconds: HeartBeatIntervalSeconds(30),
cors: Cors(['*']),
),
(request, response) async {
return CallableResult({'message': 'Callable with all options'});
},
);
// GCF Gen1 CPU option
firebase.https.onRequest(
name: 'httpsGen1',
options: const HttpsOptions(cpu: Cpu.gcfGen1()),
(request) async => Response.ok('GCF Gen1 CPU'),
);
// Custom invoker list
firebase.https.onRequest(
name: _OptionsSilly.httpsCustomInvoker,
options: const HttpsOptions(
invoker: Invoker(['user1@example.com', 'user2@example.com']),
),
(request) async => Response.ok('Custom invoker'),
);
// Pub/Sub with options
firebase.pubsub.onMessagePublished(
topic: optionsTopic,
options: const PubSubOptions(
memory: Memory(MemoryOption.mb256),
timeoutSeconds: TimeoutSeconds(120),
region: Region(SupportedRegion.usWest1),
),
(event) async {
print('Pub/Sub with options');
},
);
print('Functions registered successfully!');
});
}
/// Testing constant expression evaluation
const optionsTopic = 'options-topic';
class _OptionsSilly {
/// Testing constant expression evaluation
static const httpsCustomInvoker = 'httpsCustomInvoker';
}
// =============================================================================
// Data classes for typed callable functions
// =============================================================================
/// Request data for the greetTyped callable function.
class GreetRequest {
GreetRequest({required this.name});
factory GreetRequest.fromJson(Map<String, dynamic> json) {
return GreetRequest(name: json['name'] as String? ?? 'World');
}
final String name;
Map<String, dynamic> toJson() => {'name': name};
}
/// Response data for the greetTyped callable function.
class GreetResponse {
GreetResponse({required this.message});
final String message;
Map<String, dynamic> toJson() => {'message': message};
}