대학 동기들과 함께 제작한 안드로이드 앱의 리팩토링 과정 중, 백엔드에서 처리하면 좋겠다 싶은 기능이 있었다.
마지막 접속일이 1년 이상인 경우, 데이터를 삭제해주는 기능인데, 프론트에서는 절대로 할 수 없는 그런 기능이다...........
앱 개발 구성원이 모두 안드로이드 앱 제작만 진행했고, 서버없이 Firebase Firestore만을 사용하여 개발을 진행하고 있었기에 Firebase의 연계 프레임워크인 Function 기능을 사용해보기로 했다.
Firebase Functions란?
Firebase Functions는 Google Firebase에서 제공하는 서버리스 백엔드 기능으로, 클라우드에서 실행되는 JavaScript 또는 TypeScript 코드를 작성하여 백엔드 작업을 처리할 수 있는 서비스이다.
서버를 직접 관리할 필요 없이 특정 이벤트(예: 데이터베이스 변경, 인증, HTTP 요청 등)가 발생하면 정의된 코드를 실행할 수 있다.
작성한 함수를 배포하고, 이를 Google Clouds에 연결하여 이벤트를 발생시키고 대응할 수 있다.
구현 과정
1. Cloud Functions 설정
Firebase CLI를 설치하고, Firebase 프로젝트에서 Cloud Functions를 초기화한다.
2. 함수 작성
JavaScript, TypeScript, Python 으로 코드를 작성하여 이벤트를 처리한다.
3. 함수 테스트
로컬로 함수를 테스트한다.
4. 배포 및 모니터링
작성한 함수를 배포하고, Google Cloud 콘솔을 사용하여 로그를 확인하고 검색한다.
환경 설정하기
일단, Node.js 공식 사이트에서 최신 버전을 다운받는다.
그 다음, 관리자 권한으로 cmd를 켜준 후 Firebase CLI를 설치한다.
npm install -g firebase-tools
설치가 끝났다면, Firebase에 login 해줘야 한다.
firebase login
이미 로그인을 한 이후이기 때문에, Already logged in...가 떴다.
원하는 경로에서 firebase 프로젝트를 생성해준다. (System32에서 명령어를 실행했지만, Desktop 내 디렉터리를 만들어 진행하였다.)
여기서 필요한 기능들을 설정해준다. JS는 안한지 너무 오래라 까먹었고, TS는 써본 적이 없어 Python으로 진행해줄 예정이다.
기능 설정이 끝나면, 여러 폴더 및 파일이 생성되는데, 설정한 이름의 디렉토리 내로 들어가면 main.py 파일이 있다.
그 안에 필요한 함수를 입력해주면 된다.
# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
from firebase_functions import firestore_fn, https_fn
# The Firebase Admin SDK to access Cloud Firestore.
from firebase_admin import initialize_app, firestore
import google.cloud.firestore
app = initialize_app()
@https_fn.on_request()
def addmessage(req: https_fn.Request) -> https_fn.Response:
"""Take the text parameter passed to this HTTP endpoint and insert it into
a new document in the messages collection."""
# Grab the text parameter.
original = req.args.get("text")
if original is None:
return https_fn.Response("No text parameter provided", status=400)
firestore_client: google.cloud.firestore.Client = firestore.client()
# Push the new message into Cloud Firestore using the Firebase Admin SDK.
_, doc_ref = firestore_client.collection("messages").add({"original": original})
# Send back a message that we've successfully written the message
return https_fn.Response(f"Message with ID {doc_ref.id} added.")
@firestore_fn.on_document_created(document="messages/{pushId}")
def makeuppercase(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]) -> None:
"""Listens for new documents to be added to /messages. If the document has
an "original" field, creates an "uppercase" field containg the contents of
"original" in upper case."""
# Get the value of "original" if it exists.
if event.data is None:
return
try:
original = event.data.get("original")
except KeyError:
# No "original" field, so do nothing.
return
# Set the "uppercase" field.
print(f"Uppercasing {event.params['pushId']}: {original}")
upper = original.upper()
event.data.reference.update({"uppercase": upper})
다음은 예시 함수로, Firebase 공식 문서에서 해당 내용을 확인할 수 있다.
main.py에 입력을 완료하면, 다시 cmd로 돌아가 배포해준다.
firebase deploy
여기서 deploy success! 가 나오면 성공! (작성자는 여기서 여러 오류들을 마주했다............🫠)
Firebase Console의 Functions탭에 들어가면 잘 배포된 걸 확인할 수 있다.
'CS' 카테고리의 다른 글
[리눅스 마스터 1급] 실습 환경 구축하기(VirtualBox, Rocky 8.9) (0) | 2025.01.24 |
---|---|
[CS]네트워크 - 처리량, 지연 시간 (1) | 2024.11.09 |
[CS] MVC, MVP, MVVM 패턴에 대해 알아보자 (2) | 2024.07.13 |