|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +// [START imports] |
| 16 | +// Dependencies for callable functions. |
| 17 | +import 'package:firebase_functions/firebase_functions.dart'; |
| 18 | +// [END imports] |
| 19 | + |
| 20 | +void main(List<String> args) async { |
| 21 | + await fireUp(args, (firebase) { |
| 22 | + // [START allAdd] |
| 23 | + // [START addFunctionTrigger] |
| 24 | + // Adds two numbers to each other. |
| 25 | + firebase.https.onCall(name: 'addNumbers', (request, response) async { |
| 26 | + // [END addFunctionTrigger] |
| 27 | + // [START readAddData] |
| 28 | + // Numbers passed from the client. |
| 29 | + final data = request.data as Map<String, Object?>?; |
| 30 | + final firstNumber = data?['firstNumber']; |
| 31 | + final secondNumber = data?['secondNumber']; |
| 32 | + // [END readAddData] |
| 33 | + |
| 34 | + // [START addHttpsError] |
| 35 | + // Checking that attributes are present and are numbers. |
| 36 | + if (firstNumber is! num || secondNumber is! num) { |
| 37 | + // Throwing an HttpsError so that the client gets the error details. |
| 38 | + throw InvalidArgumentError( |
| 39 | + 'The function must be called with two arguments "firstNumber" and "secondNumber" which must both be numbers.', |
| 40 | + ); |
| 41 | + } |
| 42 | + // [END addHttpsError] |
| 43 | + |
| 44 | + // [START authIntegration] |
| 45 | + // Authentication / user information is automatically added to the request. |
| 46 | + final uid = request.auth?.uid; |
| 47 | + final token = request.auth?.token; |
| 48 | + final name = token?['name']; |
| 49 | + final picture = token?['picture']; |
| 50 | + final email = token?['email']; |
| 51 | + |
| 52 | + // Use variables to suppress 'unused' lint warnings |
| 53 | + print( |
| 54 | + 'User details: uid=$uid, name=$name, picture=$picture, email=$email', |
| 55 | + ); |
| 56 | + // [END authIntegration] |
| 57 | + |
| 58 | + // [START returnAddData] |
| 59 | + // returning result. |
| 60 | + return CallableResult({ |
| 61 | + 'firstNumber': firstNumber, |
| 62 | + 'secondNumber': secondNumber, |
| 63 | + 'operator': '+', |
| 64 | + 'operationResult': firstNumber + secondNumber, |
| 65 | + }); |
| 66 | + // [END returnAddData] |
| 67 | + }); |
| 68 | + // [END allAdd] |
| 69 | + }); |
| 70 | +} |
0 commit comments