CLASSFUNC BLOG
We Share Our Knowledge
Create Cloud functions with firebase
Dam Van Duong
5 Th09 2020 10:18
  1. Nếu bạn chưa có Project Firebase, hãy tạo 1 project mới tại https://console.firebase.google.com/, click Add project và làm theo hướng dẫn.
  2. Khi đã tạo hoặc có Project Firebase rồi, thử gọi tên nó là test-classfunc nhé,
  • Bây giờ bạn tiếp tục tạo 1 folder chứa dữ liệu của cloud function chứ nhỉ, hãy tạo 1 folder có tên “test-cloudfunctions”,
  • Tiếp theo, để chuẩn bị cho quá trình cài đặt và init cloud function, trên terminal bạn chạy: npm install --save firebase-functions@latest firebase-admin@latest và cài đặt Filebase Tools: npm install -g firebase-tools
  • Tiếp tục chạy firebse login để tiến hành đăng nhập vào firebase. firebase login.
  • Truy cập vào folder “test-cloudfunctions” -> cd test-cloudfunctions.
  • Thực hiện lệnh firebase init hoặc firebase init functions, chọn javascript để thực hiện.
  • Sau khi thực hiện xong, projects cloud functions của bạn sẽ có cấu trúc như sau:
json
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- .eslintrc.json  # Optional file containing rules for JavaScript linting.
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

trong file package.json, nếu muốn cài đặt môi trường cho cloud functions la node 10, hãy thêm "engines": {"node": "10"}.

  1. Trong file index.js, tiến hành thêm các thông tin cài đặt cần thiết.
const admin = require('firebase-admin') const serviceAccount = require('./firebaseServiceAdmin.json'); // fire json services admin account get more: https://console.firebase.google.com/project/[projectId]/settings/serviceaccounts/adminsdk admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: 'https://[projectId].firebaseio.com', });
  1. Bây giờ hãy tạo cho mình 1 functions và thực hiện deploy functions đầu tiên của mình thôi. Dưới đây là 2 ví dụ:

Tạo AddMessage() functions

// Take the text parameter passed to this HTTP endpoint and insert it into // Cloud Firestore under the path /messages/:documentId/original exports.addMessage = functions.https.onRequest(async (req, res) => {   // Grab the text parameter.   const original = req.query.text;   // Push the new message into Cloud Firestore using the Firebase Admin SDK.   const writeResult = await admin.firestore().collection('messages').add({original: original});   // Send back a message that we've succesfully written the message   res.json({result: `Message with ID: ${writeResult.id} added.`}); });

addMessage được gọi là http functions, có thể gửi request lên để lấy dữ liệu về theo các phương thức Get, Post, Put, Delete ....

tạo makeUppercase() functions

// Listens for new messages added to /messages/:documentId/original and creates an // uppercase version of the message to /messages/:documentId/uppercase exports.makeUppercase = functions.firestore().document('/messages/{documentId}')     .onCreate((snap, context) => {       // Grab the current value of what was written to Cloud Firestore.       const original = snap.data().original;       // Access the parameter `{documentId}` with `context.params`       functions.logger.log('Uppercasing', context.params.documentId, original);             const uppercase = original.toUpperCase();             // You must return a Promise when performing asynchronous tasks inside a Functions such as       // writing to Cloud Firestore.       // Setting an 'uppercase' field in Cloud Firestore document returns a Promise.       return snap.ref.set({uppercase}, {merge: true});     });

Với các functions dạng makeUppercase, hoạt động theo dạng tự động trigger khi có sự thay đổi của collection Messages, ở đây khi tạo mới messages .onCreate((snap, context), ngoài ra còn có các kiểu khác như .onDelete .onUpdate .onWrite

  1. Deploy function

Chạy lệnh : firebase deploy --only functions Hoặc nếu chỉ muốn deploy 1 functions riêng biệt. chạy lệnh firebase deploy --only functions:[function name], function name => foldername Funtionname
Ví dụ: folder api có function name test.js => firebase deploy --only functions:apiTest

Trên đây mình đã hướng dẫn các bạn việc tạo và cài đặt, deploy 1 cloud functions mới, chúc các bạn thành công

  1. Tài liệu tham khảo