Vue로 PWA 개발 - 그랜파 개발자
Firestore 트리거 기능을 이용하면 mylog가 firestore에 저장될 때 이벤트를 받을 수 있습니다.
exports.sendMylogNotification = onDocumentCreated('/mylogs/{mylogId}', (event) => {
const mylog = event.data;
console.log('New mylog created:', mylog);
});
수신한 이벤트 데이터에 방금 저장한 마이로그의 모든 정보가 저장되어 있습니다. 마이로그 userId로 독자들의 userId를 구해 푸시 알림을 전송하려고 합니다.
Firebase Cloud Functions에서 Firestore의 데이터를 가져오는 방법을 알아야 겠습니다.
To use Firestore in Firebase Cloud Functions, you need to set up the Firebase Admin SDK, which gives you access to Firestore and other Firebase services. Firebase Functions can interact with Firestore to read, write, update, or delete data, as well as respond to Firestore triggers (such as when a document is created, updated, or deleted).
Firebase Cloud Functions에서 Firestore를 사용하려면 Firestore 및 기타 Firebase 서비스에 대한 액세스를 제공하는 Firebase Admin SDK를 설정해야 합니다. Firebase Functions는 Firestore와 상호작용하여 데이터를 읽고, 쓰고, 업데이트하거나 삭제할 수 있을 뿐만 아니라 Firestore 트리거(예: 문서 생성, 업데이트 또는 삭제 시)에 응답할 수 있습니다.
Here’s how you can use Firestore in Firebase Cloud Functions:
Firebase Cloud Functions에서 Firestore를 사용하는 방법은 다음과 같습니다.
Initialize Firebase Admin SDK: You need to initialize Firebase Admin to use Firestore in functions.
Firebase Admin SDK 초기화: Firestore를 기능에서 사용하려면 Firebase Admin을 초기화해야 합니다.
Perform Firestore Operations: You can perform CRUD (Create, Read, Update, Delete) operations on Firestore data within your function.
Firestore 작업 수행: 함수 내에서 Firestore 데이터에 대해 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 수행할 수 있습니다.
Firestore Triggers: Functions can also respond to Firestore events like document creation, updates, or deletion.
Firestore 트리거: 함수는 문서 생성, 업데이트, 삭제와 같은 Firestore 이벤트에도 응답할 수 있습니다.
First, ensure that Firebase Admin SDK is initialized. Firebase Admin allows server-side interaction with Firestore.
먼저 Firebase Admin SDK가 초기화되었는지 확인하세요. Firebase 관리자는 Firestore와의 서버 측 상호작용을 허용합니다.
In your index.js (or any entry point for Firebase Functions):
index.js(또는 Firebase Functions의 진입점)에서:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK
admin.initializeApp();
This will allow you to access Firestore and other Firebase services from within your Cloud Functions.
이렇게 하면 Cloud Functions 내에서 Firestore 및 기타 Firebase 서비스에 액세스할 수 있습니다.
Here’s how you can write and read data from Firestore within a Firebase Cloud Function.
Firebase Cloud Function 내에서 Firestore의 데이터를 쓰고 읽는 방법은 다음과 같습니다.
// Import necessary Firebase SDKs
const { onRequest } = require('firebase-functions/v2/https');
// Example: Add data to Firestore
exports.addPost = onRequest(async (req, res) => {
const data = {
title: req.body.title,
content: req.body.content,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
};
try {
const docRef = await admin.firestore().collection('posts').add(data);
res.send(`Post added with ID: ${docRef.id}`);
} catch (error) {
console.error('Error adding document: ', error);
res.status(500).send('Error adding post');
}
});
// Example: Get data from Firestore
exports.getPost = onRequest(async (req, res) => {
const postId = req.query.id;
try {
const doc = await admin.firestore().collection('posts').doc(postId).get();
if (!doc.exists) {
res.status(404).send('No post found!');
} else {
res.send(doc.data());
}
} catch (error) {
console.error('Error getting document: ', error);
res.status(500).send('Error fetching post');
}
});
Adding Data: 데이터 추가:
The addPost function adds a new document to the posts collection in Firestore using admin.firestore().collection('posts').add(data).
addPost 함수는 admin.firestore().collection('posts').add(data)를 사용하여 Firestore의 posts 컬렉션에 새 문서를 추가합니다.
It includes a createdAt timestamp using admin.firestore.FieldValue.serverTimestamp().
admin.firestore.FieldValue.serverTimestamp()를 사용하는 createdAt 타임스탬프를 포함합니다.
Reading Data: 데이터 읽기:
You can trigger Cloud Functions when Firestore data changes, such as when a document is created, updated, or deleted.
문서가 생성, 업데이트, 삭제되는 등 Firestore 데이터가 변경되면 Cloud Functions를 트리거할 수 있습니다.
const { onDocumentCreated } = require('firebase-functions/v2/firestore');
// Trigger when a new document is created in the 'posts' collection
exports.notifyOnNewPost = onDocumentCreated('/posts/{postId}', (event) => {
const newPostData = event.data;
console.log('New post created with title:', newPostData.title);
});
You can update specific fields in Firestore using update or set with merge: true option.
update 또는 merge: true 옵션과 함께 set을 사용하여 Firestore의 특정 필드를 업데이트할 수 있습니다.
// Update a specific field in a Firestore document
exports.updatePost = onRequest(async (req, res) => {
const postId = req.body.id;
const newContent = req.body.content;
try {
await admin.firestore().collection('posts').doc(postId).update({
content: newContent,
updatedAt: admin.firestore.FieldValue.serverTimestamp(),
});
res.send(`Post ${postId} updated successfully`);
} catch (error) {
console.error('Error updating post: ', error);
res.status(500).send('Error updating post');
}
});
You can delete a document using the delete method.
delete 메소드를 사용하여 문서를 삭제할 수 있습니다.
// Delete a document from Firestore
exports.deletePost = onRequest(async (req, res) => {
const postId = req.body.id;
try {
await admin.firestore().collection('posts').doc(postId).delete();
res.send(`Post ${postId} deleted successfully`);
} catch (error) {
console.error('Error deleting post: ', error);
res.status(500).send('Error deleting post');
}
});
To deploy these functions to Firebase, run the following command:
이러한 기능을 Firebase에 배포하려면 다음 명령어를 실행하세요.
firebase deploy --only functions
This will deploy all the functions you’ve defined in your index.js or functions file to Firebase.
이렇게 하면 index.js 또는 함수 파일에 정의한 모든 함수가 Firebase에 배포됩니다.
By following this approach, you can fully utilize Firestore in your Firebase Cloud Functions to interact with your Firestore database in various ways!
이 접근 방식을 따르면 Firebase Cloud Functions에서 Firestore를 최대한 활용하여 다양한 방식으로 Firestore 데이터베이스와 상호작용할 수 있습니다!