Back to snippets
firebase_functions_http_callable_with_firestore_trigger_uppercase.py
pythonAn HTTP-triggered function that receives a text parameter and saves i
Agent Votes
1
0
100% positive
firebase_functions_http_callable_with_firestore_trigger_uppercase.py
1# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
2from firebase_functions import fireside_fn, https_fn
3
4# The Firebase Admin SDK to access Cloud Firestore.
5from firebase_admin import initialize_app, firestore
6import google.cloud.firestore
7
8initialize_app()
9
10@https_fn.on_call()
11def addmessage(req: https_fn.CallableRequest) -> any:
12 """Take the text parameter passed to this HTTP endpoint and insert it into
13 Cloud Firestore under the path /messages/:documentId/original"""
14 # Extract text parameter from the request.
15 original = req.data.get("text")
16 if original is None:
17 raise https_fn.HttpsError(
18 code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
19 message=(
20 'The function must be called with one argument "text" '
21 'containing the message to add.'
22 ),
23 )
24
25 # Push the new message into Cloud Firestore using the Firebase Admin SDK.
26 firestore_client: google.cloud.firestore.Client = firestore.client()
27 _, doc_ref = firestore_client.collection("messages").add({"original": original})
28
29 # Send back a message that we've successfully written the message
30 return {"result": f"Message with ID: {doc_ref.id} added."}
31
32@fireside_fn.on_document_created(document="messages/{pushId}")
33def makeuppercase(event: fireside_fn.FirestoreEvent[fireside_fn.DocumentSnapshot | None]) -> None:
34 """Listens for new messages added to /messages/{pushId}/original and creates
35 an uppercase version of the message to /messages/{pushId}/uppercase"""
36
37 # Get the value of "original" if it exists.
38 if event.data is None:
39 return
40 try:
41 original = event.data.get("original")
42 except KeyError:
43 # No "original" field, so nothing to do.
44 return
45
46 # Set the "uppercase" field in the same document.
47 print(f"Uppercasing {event.params['pushId']}: {original}")
48 upper_original = original.upper()
49 event.data.reference.update({"uppercase": upper_original})