CLASSFUNC BLOG

We Share Our Knowledge
Site Search

Cloud Functions trong firebase

Thanh Nguyễn ✍︎︎ 21-08-2020

Cài đặt

  • Node js
  • Npm
  • Firebase CLI * npm install -g firebase-tools

    Chạy firebase login để login và xác thực firebase tool.

    Chạy firebase init functions để cài đặt functions firebase cho project của bạn.

    Cấu trúc thư mục sau khi cài đặt như sau.

myproject
 +- .firebaserc    #hidden file giúp bạn chuyển đổi nhanh chóng giữa các project
 |                 
 |
 +- firebase.json  # Mô tả các thuộc tính cho porject 
 |
 +- functions/     # thư mục chứa function code
      |
      +- package.json  # npm package file khai báo các dependence dùng cho Cloud Functions
      |
      +- index.js      # file code chính của Cloud Functions
      |
      +- node_modules/ # thư mục chứa các source dependence đã đc cài đặt (khai báo trong package.json)
  • Trong index.js coppy đoạn code sau.
exports.helloWorldTest = functions.https.onRequest((request, response) => {
 response.send("<p>Hello from Firebase!</p>");
});
  • onRequest(non-null express.Request, non-null express.Response) tham số 1 là request gửi lên, 2 là response trả về(Request,Response)
  • Để deploy functions:

    firebase deploy --only functions

  • Đây là kết quả khi deploy

    alt

  • function url chính là endpoint để truy cập tới function mà bạn vừa viết, hãy dán nó vào trình dyệt và đây là kết quả.

    alt

    Tài liệu tham khảo:https://firebase.google.com/docs/functions/get-started