Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
**/.firebase
**/.firebaserc
**/.runtimeconfig.json
**/functions.yaml
**/firestore-debug.log
*/npm-debug.log
lerna-debug.log
*~
Expand Down
5 changes: 5 additions & 0 deletions Dart/quickstarts/https-increment-number/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.dart_tool/
.packages
build/
*.dart_tool
pubspec.lock
48 changes: 48 additions & 0 deletions Dart/quickstarts/https-increment-number/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# HTTPS Increment Number Quickstart

This quickstart demonstrates how to handle HTTP requests for Cloud Functions using Dart.
It features two endpoints:
- `incrementLocal`: Simple POST request that takes a local count and returns it incremented by 1.
- `incrementSynced`: GET and POST endpoints that sync a counter variable to Firestore, returning the newly updated count.



## Local Testing

First, fetch dependencies:
```bash
dart pub get
```

Then, you can use the Firebase CLI to test the function locally. To ensure both endpoints work properly, make sure to start both the functions and firestore emulators:
```bash
firebase emulators:start --project="demo-example" --only firestore,functions
```

### Testing `incrementLocal`

In a separate terminal, use cURL to POST to the function (replace the URL with the one provided by the emulator):

```bash
curl -X POST http://127.0.0.1:5001/demo-example/us-central1/increment-local \
-H "Content-Type: application/json" \
-d '{"count": 5}'
```

You should see:
```json
{"message":"Local increment complete!","newCount":6}
```

### Testing `incrementSynced`

To test using Firestore, fetch the initial count:
```bash
curl -X GET http://127.0.0.1:5001/demo-example/us-central1/increment-synced
```

Then increment it using POST:
```bash
curl -X POST http://127.0.0.1:5001/demo-example/us-central1/increment-synced \
-H "Content-Type: application/json"
```
107 changes: 107 additions & 0 deletions Dart/quickstarts/https-increment-number/bin/server.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import 'dart:convert';
import 'package:dart_firebase_admin/dart_firebase_admin.dart';
import 'package:firebase_functions/firebase_functions.dart';
import 'package:google_cloud_firestore/google_cloud_firestore.dart';

const incrementCallable = 'incrementSynced';

class IncrementResponse {
final String message;
final int newCount;

IncrementResponse({required this.message, required this.newCount});

Map<String, dynamic> toJson() => {
'message': message,
'newCount': newCount,
};
}

void main(List<String> args) async {
await fireUp(args, (firebase) {

// [START dartHttpIncrementLocal]
firebase.https.onRequest(name: 'incrementLocal', (request) async {
print('Incrementing counter locally...');

if (request.method != 'POST') {
return Response(405, body: 'Method Not Allowed');
}

int currentCount = 0;
final bodyString = await request.readAsString();
if (bodyString.isNotEmpty) {
try {
final body = jsonDecode(bodyString) as Map<String, dynamic>;
currentCount = body['count'] as int? ?? 0;
} catch (e) {
return Response.badRequest(body: 'Invalid JSON request');
}
}

final response = IncrementResponse(
message: 'Local increment complete!',
newCount: currentCount + 1,
);

return Response(
200,
body: jsonEncode(response.toJson()),
headers: {'Content-Type': 'application/json'},
);
});
// [END dartHttpIncrementLocal]

// [START dartHttpIncrementSynced]
firebase.https.onRequest(name: incrementCallable, (request) async {
print('Processing synced counter request...');

// Get firestore admin instance
final firestore = FirebaseApp.instance.firestore();

// Get a reference to the counter document
final counterDoc = firestore.collection('counters').doc('global');

if (request.method == 'GET') {
// Handle GET request to read the current counter
final snapshot = await counterDoc.get();
final currentCount = snapshot.data()?['count'] as int? ?? 0;

final response = IncrementResponse(
message: 'Cloud-sync fetched!',
newCount: currentCount,
);

return Response(
200,
body: jsonEncode(response.toJson()),
headers: {'Content-Type': 'application/json'},
);
} else if (request.method == 'POST') {
// Handle POST request to increment the counter
final snapshot = await counterDoc.get();
final currentCount = snapshot.data()?['count'] as int? ?? 0;

// Increment count by one
await counterDoc.set({
'count': FieldValue.increment(1),
}, options: SetOptions.merge());

final response = IncrementResponse(
message: 'Cloud-sync complete!',
newCount: currentCount + 1,
);

return Response(
200,
body: jsonEncode(response.toJson()),
headers: {'Content-Type': 'application/json'},
);
} else {
return Response(405, body: 'Method Not Allowed');
}
});
// [END dartHttpIncrementSynced]

});
}
9 changes: 9 additions & 0 deletions Dart/quickstarts/https-increment-number/firebase.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"functions": {
"source": ".",
"codebase": "dart-quickstarts-https-increment-number"
},
"firestore": {
"rules": "firestore.rules"
}
}
8 changes: 8 additions & 0 deletions Dart/quickstarts/https-increment-number/firestore.rules
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
}
}
}
38 changes: 38 additions & 0 deletions Dart/quickstarts/https-increment-number/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: https_increment_number
description: HTTPS trigger examples showcasing state increment operations.
publish_to: none

environment:
sdk: ^3.11.0

dependencies:
firebase_functions:
git:
url: https://github.com/firebase/firebase-functions-dart
ref: main
dart_firebase_admin:
git:
url: https://github.com/firebase/firebase-admin-dart
path: packages/dart_firebase_admin
ref: main
google_cloud_firestore:
git:
url: https://github.com/firebase/firebase-admin-dart
path: packages/google_cloud_firestore
ref: main

dev_dependencies:
build_runner: ^2.10.5
lints: ^6.0.0

dependency_overrides:
dart_firebase_admin:
git:
url: https://github.com/firebase/firebase-admin-dart
path: packages/dart_firebase_admin
ref: main
google_cloud_firestore:
git:
url: https://github.com/firebase/firebase-admin-dart
path: packages/google_cloud_firestore
ref: main
Loading