2017-06-17 37 views
5

Tôi đã các chức năng sau đó lắng nghe một sự kiện onWrite cho kích hoạt một cơ sở dữ liệu như vậy:căn cứ hỏa lực: Kiểm tra cho 'viết hoặc xóa' cho các sự kiện onWrite

exports.sendNotifications = functions.database.ref('/events/{eventId}/registered') 
     .onWrite(event => { 

      ... 
     }); 

Chức năng ở trên được gọi là bất kể nút là đã xóa hoặc đã thêm. Làm cách nào để kiểm tra xem sự kiện onWrite có phải là sự kiện 'xóa' cho nút cụ thể đó hay sự kiện 'thêm', chẳng hạn chức năng này chỉ được gọi khi nó là sự kiện 'thêm'.

Trả lời

5

event được chuyển vào hàm chứa cả dữ liệu trước đó và dữ liệu mới cho vị trí đã kích hoạt hàm. Với hai mẩu thông tin này, bạn có thể khấu trừ cho dù đó là viết mới, cập nhật hay xóa.

Từ Firebase documentation for database functions:

exports.makeUppercase = functions.database.ref('/messages/{pushId}/original') 
.onWrite(event => { 
    // Only edit data when it is first created. 
    if (event.data.previous.exists()) { 
    return; 
    } 
    // Exit when the data is deleted. 
    if (!event.data.exists()) { 
    return; 
    } 
+0

Đảm bảo bạn trả về null từ các hàm firebase nếu bạn không thực hiện bất kỳ tác vụ nào –

0

Nếu thay đổi của bạn với Cloud FireStore sau đó nó sẽ là:

// Only edit data when it is first created. 
    if (event.data.previous.exists) { 
    return; 
    } 
    // Exit when the data is deleted. 
    if (!event.data.exists) { 
    return; 
    } 
0

Sau khi đọc bài viết sau đây, thêm kiểm tra khác trên các yếu tố sự kiện với tuyên bố if-then có một số lợi ích: https://firebase.googleblog.com/2017/07/cloud-functions-realtime-database.html

exports.sendNotification = functions.database 
     .ref("/messages/{messageId}").onWrite(event => { 
    if (event.data.exists() && !event.data.previous.exists()) { 
     // This is a new message, not a change or a delete. 
     // Put code here 
    } 
}) 

Nếu đọc từ cơ sở dữ liệu không thành công (có thể là lỗi mạng ???), thì event.data.previous.exists() sẽ là sai. Việc bổ sung event.data.exists() đảm bảo yếu tố sự kiện thực tế có dữ liệu mà bạn có thể sử dụng.

Các vấn đề liên quan