Cloud Functions สำหรับ SDK ไคลเอ็นต์ Firebase ช่วยให้คุณเรียกใช้ฟังก์ชันได้โดยตรงจากแอป Firebase ในการเรียกใช้ฟังก์ชันจากแอปของคุณด้วยวิธีนี้ให้เขียนและปรับใช้ฟังก์ชัน HTTPS Callable ใน Cloud Functions จากนั้นเพิ่มตรรกะไคลเอ็นต์เพื่อเรียกใช้ฟังก์ชันจากแอปของคุณ
สิ่งสำคัญคือต้องจำไว้ว่าฟังก์ชันที่เรียกได้ของ HTTPS นั้นคล้ายกัน แต่ ไม่เหมือนกับ ฟังก์ชัน HTTP ในการใช้ฟังก์ชันที่เรียกใช้ HTTPS คุณต้องใช้ไคลเอนต์ SDK สำหรับแพลตฟอร์มของคุณร่วมกับ functions.https
https backend API (หรือใช้โปรโตคอล) Callables มีความแตกต่างที่สำคัญเหล่านี้จากฟังก์ชัน HTTP:
- เมื่อมีการเรียกใช้โทเค็น Firebase Authentication และ FCM จะรวมอยู่ในคำขอโดยอัตโนมัติ
- ทริกเกอร์
functions.https.onCall
จะยกเลิกการเชื่อมต่อเนื้อหาคำขอโดยอัตโนมัติและตรวจสอบโทเค็นการตรวจสอบสิทธิ์
Firebase SDK for Cloud Functions v0.9.1 และสูงกว่าทำงานร่วมกับเวอร์ชันขั้นต่ำของไคลเอ็นต์ Firebase SDK เหล่านี้เพื่อรองรับฟังก์ชันที่เรียกใช้ HTTPS:
- Firebase SDK สำหรับ iOS 7.7.0
- Firebase SDK สำหรับ Android 19.2.0
- Firebase JavaScript SDK 8.2.9
หากคุณต้องการเพิ่มฟังก์ชันที่คล้ายกันให้กับแอปที่สร้างขึ้นบนแพลตฟอร์มที่ไม่รองรับโปรดดูข้อกำหนด โปรโตคอลสำหรับ https.onCall
ส่วนที่เหลือของคู่มือนี้ให้คำแนะนำเกี่ยวกับวิธีการเขียนปรับใช้และเรียกใช้ฟังก์ชันที่เรียกใช้ HTTPS สำหรับ iOS, Android, เว็บ, C ++ และ Unity
เขียนและปรับใช้ฟังก์ชันที่เรียกได้
ใช้ functions.https.onCall
เพื่อสร้าง functions.https.onCall
ใช้ HTTPS วิธีนี้ใช้สองพารามิเตอร์: data
และ context
ทางเลือก:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
สำหรับฟังก์ชันที่เรียกได้ที่บันทึกข้อความไปยังฐานข้อมูลแบบเรียลไทม์เช่น data
อาจมีข้อความในขณะที่พารามิเตอร์ context
แสดงถึงข้อมูลการตรวจสอบสิทธิ์ของผู้ใช้:
// Message text passed from the client.
const text = data.text;
// Authentication / user information is automatically added to the request.
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;
ระยะห่างระหว่างตำแหน่งของฟังก์ชันที่เรียกได้และตำแหน่งของไคลเอนต์ที่โทรสามารถสร้างเวลาแฝงของเครือข่ายได้ เพื่อเพิ่มประสิทธิภาพการทำงานให้พิจารณาการระบุ ตำแหน่งของฟังก์ชัน ที่สามารถใช้ได้และตรวจสอบให้แน่ใจว่าได้จัดตำแหน่งของที่โทรได้ให้ตรงกับตำแหน่งที่ตั้งไว้เมื่อคุณ เริ่มต้น SDK ในฝั่งไคลเอ็นต์
ส่งผลลัพธ์กลับ
หากต้องการส่งข้อมูลกลับไปยังไคลเอ็นต์ให้ส่งคืนข้อมูลที่สามารถเข้ารหัส JSON ได้ ตัวอย่างเช่นในการส่งคืนผลลัพธ์ของการดำเนินการเพิ่มเติม:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
หากต้องการส่งคืนข้อมูลหลังจากการดำเนินการแบบอะซิงโครนัสให้ส่งคืนคำสัญญา ข้อมูลที่สัญญาจะส่งกลับไปยังไคลเอนต์ ตัวอย่างเช่นคุณสามารถส่งคืนข้อความที่ผ่านการฆ่าเชื้อแล้วซึ่งฟังก์ชันที่เรียกได้นั้นเขียนไปยังฐานข้อมูลแบบเรียลไทม์:
// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize the message.
return admin.database().ref('/messages').push({
text: sanitizedMessage,
author: { uid, name, picture, email },
}).then(() => {
console.log('New Message written');
// Returning the sanitized message to the client.
return { text: sanitizedMessage };
})
จัดการข้อผิดพลาด
เพื่อให้แน่ใจว่าไคลเอนต์ได้รับรายละเอียดข้อผิดพลาดที่เป็นประโยชน์ให้ส่งคืนข้อผิดพลาดจากการโทรโดยการโยน (หรือส่งคืนสัญญาที่ถูกปฏิเสธด้วย) ตัวอย่างของ functions.https.HttpsError
ข้อผิดพลาดนี้มีแอตทริบิวต์ code
ที่สามารถเป็นค่าใดค่าหนึ่งที่แสดงอยู่ใน functions.https.HttpsError
ข้อผิดพลาดยังมี message
สตริงซึ่งมีค่าเริ่มต้นเป็นสตริงว่าง นอกจากนี้ยังสามารถมีช่อง details
พร้อมค่าตามอำเภอใจ หากเกิดข้อผิดพลาดอื่นที่ไม่ใช่ HttpsError
จากฟังก์ชันของคุณไคลเอนต์ของคุณจะได้รับข้อผิดพลาดพร้อมข้อความ INTERNAL
และรหัส internal
แทน
ตัวอย่างเช่นฟังก์ชันอาจส่งข้อผิดพลาดในการตรวจสอบข้อมูลและการพิสูจน์ตัวตนพร้อมข้อความแสดงข้อผิดพลาดเพื่อกลับไปยังไคลเอนต์ที่เรียก
// Checking attribute.
if (!(typeof text === 'string') || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
'one arguments "text" containing the message text to add.');
}
// Checking that the user is authenticated.
if (!context.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
'while authenticated.');
}
ปรับใช้ฟังก์ชันที่เรียกได้
หลังจากที่คุณบันทึกฟังก์ชันที่เรียกได้ที่เสร็จสมบูรณ์ภายใน index.js
ฟังก์ชันนั้นจะถูกปรับใช้พร้อมกับฟังก์ชันอื่น ๆ ทั้งหมดเมื่อคุณเรียก firebase deploy
ในการปรับใช้เฉพาะ callable ให้ใช้ --only
อาร์กิวเมนต์ดังที่แสดงเพื่อดำเนินการ ปรับใช้บางส่วน :
$ firebase deploy --only functions:addMessage
หากคุณพบข้อผิดพลาดเกี่ยวกับสิทธิ์เมื่อปรับใช้ฟังก์ชันตรวจสอบให้แน่ใจว่าได้กำหนด บทบาท IAM ที่เหมาะสมให้กับผู้ใช้ที่รันคำสั่งการปรับใช้
ตั้งค่าสภาพแวดล้อมการพัฒนาไคลเอ็นต์ของคุณ
ตรวจสอบให้แน่ใจว่าคุณมีคุณสมบัติตรงตามข้อกำหนดเบื้องต้นจากนั้นเพิ่มการอ้างอิงที่จำเป็นและไลบรารีไคลเอ็นต์ลงในแอปของคุณ
iOS
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป iOS ของคุณ
- เพิ่ม Cloud Functions pod ใน
Podfile
ของคุณ:pod 'Firebase/Functions'
- บันทึกไฟล์จากนั้นเรียกใช้:
pod install
เว็บ
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในเว็บแอปของ คุณ
- เพิ่มไลบรารีไคลเอ็นต์ Firebase core และ Cloud Functions ลงในแอปของคุณ:
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-functions.js"></script>
นอกจากนี้ Cloud Functions SDK ยังพร้อมใช้งานเป็นแพ็คเกจ npm
- รันคำสั่งต่อไปนี้จากเทอร์มินัลของคุณ:
npm install firebase@8.2.9 --save
- ต้องใช้ทั้ง Firebase core และ Cloud Functions ด้วยตนเอง:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Java
ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android ของคุณ
ใช้ Firebase Android BoM ประกาศการพึ่งพาไลบรารี Android ของ Cloud Functions ใน โมดูล ของคุณ (ระดับแอป) ไฟล์ Gradle (โดยทั่วไปคือ
app/build.gradle
)dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.5.0') // Declare the dependency for the Cloud Functions library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-functions' }
เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ
(ทางเลือก) ประกาศการอ้างอิงไลบรารี Firebase โดยไม่ต้อง ใช้ BoM
หากคุณเลือกที่จะไม่ใช้ Firebase BoM คุณต้องระบุไลบรารี Firebase แต่ละเวอร์ชันในบรรทัดการอ้างอิง
โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลาย ไลบรารีในแอปของคุณเราขอแนะนำอย่างยิ่งให้ใช้ BoM เพื่อจัดการเวอร์ชันไลบรารีซึ่งจะช่วยให้มั่นใจได้ว่าทุกเวอร์ชันจะเข้ากันได้
dependencies { // Declare the dependency for the Cloud Functions library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-functions:19.2.0' }
โคตรลิน + KTX
ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในแอป Android ของคุณ
ใช้ Firebase Android BoM ประกาศการพึ่งพาไลบรารี Android ของ Cloud Functions ใน โมดูล ของคุณ (ระดับแอป) ไฟล์ Gradle (โดยทั่วไปคือ
app/build.gradle
)dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.5.0') // Declare the dependency for the Cloud Functions library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-functions-ktx' }
เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ
(ทางเลือก) ประกาศการอ้างอิงไลบรารี Firebase โดยไม่ต้อง ใช้ BoM
หากคุณเลือกที่จะไม่ใช้ Firebase BoM คุณต้องระบุไลบรารี Firebase แต่ละเวอร์ชันในบรรทัดการอ้างอิง
โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลาย ไลบรารีในแอปของคุณเราขอแนะนำอย่างยิ่งให้ใช้ BoM เพื่อจัดการเวอร์ชันไลบรารีซึ่งจะช่วยให้มั่นใจได้ว่าทุกเวอร์ชันจะเข้ากันได้
dependencies { // Declare the dependency for the Cloud Functions library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-functions-ktx:19.2.0' }
C ++
สำหรับ C ++ กับ Android :
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโปรเจ็กต์ C ++ ของ คุณ
- เพิ่ม
firebase_functions
ห้องสมุดที่คุณCMakeLists.txt
ไฟล์
สำหรับ C ++ กับ iOS :
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโปรเจ็กต์ C ++ ของ คุณ
- เพิ่ม Cloud Functions pod ใน
Podfile
ของคุณ:pod 'Firebase/Functions'
- บันทึกไฟล์จากนั้นเรียกใช้:
pod install
- เพิ่ม Firebase core และ Cloud Functions frameworks จาก Firebase C ++ SDK ไปยังโปรเจ็กต์ Xcode ของคุณ
-
firebase.framework
-
firebase_functions.framework
-
ความสามัคคี
- ทำตามคำแนะนำเพื่อ เพิ่ม Firebase ในโปรเจ็กต์ Unity
- เพิ่ม
FirebaseFunctions.unitypackage
จาก Firebase Unity SDK ลงในโปรเจ็กต์ Unity
เริ่มต้นไคลเอ็นต์ SDK
เริ่มต้นอินสแตนซ์ของ Cloud Functions:
รวดเร็ว
lazy var functions = Functions.functions()
วัตถุประสงค์ -C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
เว็บ
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
// Initialize Cloud Functions through Firebase
var functions = firebase.functions();
Java
private FirebaseFunctions mFunctions; // ... mFunctions = FirebaseFunctions.getInstance();
โคตรลิน + KTX
private lateinit var functions: FirebaseFunctions // ... functions = Firebase.functions
C ++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
ความสามัคคี
functions = Firebase.Functions.DefaultInstance;
เรียกใช้ฟังก์ชัน
รวดเร็ว
functions.httpsCallable("addMessage").call(["text": inputField.text]) { (result, error) in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
if let text = (result?.data as? [String: Any])?["text"] as? String {
self.resultField.text = text
}
}
วัตถุประสงค์ -C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
self->_resultField.text = result.data[@"text"];
}];
เว็บ
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Java
private Task<String> addMessage(String text) { // Create the arguments to the callable function. Map<String, Object> data = new HashMap<>(); data.put("text", text); data.put("push", true); return mFunctions .getHttpsCallable("addMessage") .call(data) .continueWith(new Continuation<HttpsCallableResult, String>() { @Override public String then(@NonNull Task<HttpsCallableResult> task) throws Exception { // This continuation runs on either success or failure, but if the task // has failed then getResult() will throw an Exception which will be // propagated down. String result = (String) task.getResult().getData(); return result; } }); }
โคตรลิน + KTX
private fun addMessage(text: String): Task<String> { // Create the arguments to the callable function. val data = hashMapOf( "text" to text, "push" to true ) return functions .getHttpsCallable("addMessage") .call(data) .continueWith { task -> // This continuation runs on either success or failure, but if the task // has failed then result will throw an Exception which will be // propagated down. val result = task.result?.data as String result } }
C ++
firebase::Future<firebase::functions::HttpsCallableResult> AddMessage(
const std::string& text) {
// Create the arguments to the callable function.
firebase::Variant data = firebase::Variant::EmptyMap();
data.map()["text"] = firebase::Variant(text);
data.map()["push"] = true;
// Call the function and add a callback for the result.
firebase::functions::HttpsCallableReference doSomething =
functions->GetHttpsCallable("addMessage");
return doSomething.Call(data);
}
ความสามัคคี
private Task<string> addMessage(string text) {
// Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = text;
data["push"] = true;
// Call the function and extract the operation from the result.
var function = functions.GetHttpsCallable("addMessage");
return function.CallAsync(data).ContinueWith((task) => {
return (string) task.Result.Data;
});
}
จัดการข้อผิดพลาดในไคลเอนต์
ไคลเอนต์ได้รับข้อผิดพลาดหากเซิร์ฟเวอร์ส่งข้อผิดพลาดหรือหากสัญญาผลลัพธ์ถูกปฏิเสธ
หากข้อผิดพลาดที่ส่งกลับมาจากฟังก์ชันเป็น function.https.HttpsError
จากนั้นไคลเอนต์จะได้รับ code
ข้อผิดพลาด message
และ details
จากข้อผิดพลาดของเซิร์ฟเวอร์ มิฉะนั้นข้อผิดพลาดจะมีข้อความ INTERNAL
และรหัส INTERNAL
ดูคำแนะนำสำหรับวิธี จัดการข้อผิดพลาด ในฟังก์ชันที่เรียกได้ของคุณ
รวดเร็ว
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
วัตถุประสงค์ -C
if (error) {
if (error.domain == FIRFunctionsErrorDomain) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
}
// ...
}
เว็บ
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
})
.catch((error) => {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
// ...
});
Java
addMessage(inputMessage) .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Exception e = task.getException(); if (e instanceof FirebaseFunctionsException) { FirebaseFunctionsException ffe = (FirebaseFunctionsException) e; FirebaseFunctionsException.Code code = ffe.getCode(); Object details = ffe.getDetails(); } // ... } // ... } });
โคตรลิน + KTX
addMessage(inputMessage) .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } // ... } // ... })
C ++
void OnAddMessageCallback(
const firebase::Future<firebase::functions::HttpsCallableResult>& future) {
if (future.error() != firebase::functions::kErrorNone) {
// Function error code, will be kErrorInternal if the failure was not
// handled properly in the function call.
auto code = static_cast<firebase::functions::Error>(future.error());
// Display the error in the UI.
DisplayError(code, future.error_message());
return;
}
const firebase::functions::HttpsCallableResult *result = future.result();
firebase::Variant data = result->data();
// This will assert if the result returned from the function wasn't a string.
std::string message = data.string_value();
// Display the result in the UI.
DisplayResult(message);
}
// ...
// ...
auto future = AddMessage(message);
future.OnCompletion(OnAddMessageCallback);
// ...
ความสามัคคี
addMessage(text).ContinueWith((task) => {
if (task.IsFaulted) {
foreach (var inner in task.Exception.InnerExceptions) {
if (inner is FunctionsException) {
var e = (FunctionsException) inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.ErrorMessage;
}
}
} else {
string result = task.Result;
}
});