React Native App 을 개발하면서 Firebase 를 서버 대용으로 활용하고 있습니다.
특히 데이터베이스를 Firestore 를 사용하는데 앱 사용자에게 특정 조건이 되었을 때 뭔가 준비된 서비스를 제공하는 것을 어떻게 만들지에 대한 고민이 되었습니다.
별도 서비스용 서버를 구축 및 운영하는 것이 아니므로 서버 로직이 필요한 서비스를 어떻게 만들지에 대한 고민을 하다가 Cloud Fuction 을 알게되었습니다.
직접 앱 서비스에 적용해보고 사용하게 되어 해당 내용을 정리하고 공유하고자 합니다.
그럼 일단 Firebase Cloud Fuction이 무엇이고 어떤 기능을 할 수 있는지 알아 보겠습니다.
1. Firebase Cloud Functions 이란?
서버리스(Serverless) 환경에서 실행되는 코드로, Firebase 및 Google Cloud 서비스에서 발생하는 특정 이벤트에 따라 자동으로 실행되는 함수입니다. 사용자는 서버를 직접 관리할 필요 없이, Google의 인프라에서 코드를 실행할 수 있습니다.
https://firebase.google.com/docs/functions?hl=ko
Cloud Functions for Firebase
Firebase용 Cloud Functions는 Firebase 기능과 HTTPS 요청에 의해 트리거되는 이벤트에 응답하여 백엔드 코드를 자동으로 실행할 수 있는 서버리스 프레임워크입니다.
firebase.google.com
👉 자세한 설명은 구글 공식 문서를 참고하세요
2. 주요 특징 및 장점
- 이벤트 기반 실행
: Firestore 데이터 변경, 사용자 인증, HTTP 요청 등 다양한 이벤트에 따라 자동으로 실행됩니다. - 서버 관리 불필요
: 서버 인프라를 직접 관리할 필요가 없어 개발 및 유지보수가 간편합니다. - 확장성
: 트래픽이 증가하면 자동으로 확장되어 안정적인 성능을 제공합니다. - 다양한 통합 가능
: Firebase 서비스 및 외부 API와 쉽게 연동할 수 있습니다.
3. 대표적인 사용 사례
- 신규 사용자 가입 시 환영 이메일 발송
- Firestore 데이터 변경 시 알림 전송
- 이미지 업로드시 썸네일 자동 생성
- 주기적으로 데이터 정리 및 백업 작업 수행
- 예약 알림 발송 및 관리
4. 사용전 준비사항
- firebase console에서 프로젝트 생성 (이미 사용중인 프로젝트가 있으면 skip)
: 왼쪽 메뉴의 '빌드' 에서 Functions 선택
: 시작하기 버튼으로 활성화 함 - Blaze 요금제 가입 (무료 사용량 초과시에 과금)
- PC에 node.js, npm 설치
- 사용가능 언어 : javascript, typescript, python
5. 설정 방법
- Firebase CLI 설치 및 초기화
npm install -g firebase-tools
- firebase login
: PC 터미널에서 로그인 하기 - firebase init functions
: functions 기능 초기화 작업으로 몇 단계 초기화 과정 및 질문에 대한 대응 필요
6. 프로젝트 초기화 과정
1) Please select an option:
? Please select an option:
- Use an existing project
- Create a new project
- Add Firebase to an existing Google Cloud Platform project
- Don't set up a default project
선택 방법:
이미 Firebase 콘솔에서 프로젝트를 생성한 상태이므로,
👉 "Use an existing project" 를 선택합니다.
2) Select a default Firebase project for this directory:
? Select a default Firebase project for this directory:
picmoment-dev (picmoment)
another-project-id (another-project)
선택 방법:
현재 연결하고자 하는 프로젝트를 선택합니다.
👉 예: "picmoment-dev (picmoment)"
3) Detected existing codebase(s): default
Detected existing codebase(s): default ?
Would you like to initialize a new codebase, or overwrite an existing one?
- Initialize
- Overwrite
선택 방법:
이미 기존 코드베이스가 감지된 경우 두 가지 선택지가 있습니다.
- Initialize (추천): 기존 코드베이스를 유지하면서 새로운 코드베이스를 추가로 생성합니다.
기존 함수를 유지하고 새로운 기능을 별도 코드베이스로 관리할 때 적합합니다.
- Overwrite: 기존 코드베이스를 덮어쓰고 처음부터 다시 설정합니다.
기존 함수가 필요 없거나 처음부터 다시 설정할 때 사용합니다.
👉 일반적으로는 기존 코드가 있다면 "Initialize" 를 선택하는 것이 안전합니다.
4) What should be the name of this codebase?
? What should be the name of this codebase?
선택 방법:
이름은 자유롭게 지정할 수 있으며, 주로 다음과 같은 규칙을 따릅니다.
- 소문자, 숫자, 하이픈(-) 사용 가능
- 공백이나 특수문자는 사용하지 않음
- 의미 있는 이름 권장 (예: `functions`, `notifications`, `reminder-functions` 등)
👉 예시 추천 이름: `functions` 또는 `reminder-functions`
5) 프로젝트 초기화 완료 후 프로젝트 구조
myproject
+- .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
👉 Node.js의 경우 초기화 중에 생성된 package.json 파일에는 중요한 키인 "engines": {"node": "18"}이 포함되어 있습니다.
이 키는 함수 작성 및 배포를 위한 Node.js 버전을 의미합니다.
6) 질문에 대한 전체적인 대응 예시
? Please select an option: Use an existing project ?
Select a default Firebase project for this directory
: picmoment-dev (picmoment)
? Would you like to initialize a new codebase, or overwrite an existing one? Initialize
? What should be the name of this codebase? functions
7. Functions 코드 생성 후 배포하기
- 설정이 완료되면 다음 명령어로 배포를 진행하세요:
firebase deploy --only functions
- 배포 결과 확인 하기
firebase functions:list
👉 추가로 firebase console의 Functions 메뉴에서 확인 가능
8. 추가적인 설정 과정 필요 여부
- Firebase 콘솔에서 이미 프로젝트가 생성되어 있다면, 로컬 환경에서 위의 초기화 과정을 통해 연결만 하면 됩니다. 별도의 추가적인 설정 과정은 필요하지 않습니다.
- 단, 예약 알림 발송과 같은 Scheduled Functions(예약 함수)을 사용하려면 Google Cloud Platform(GCP)에서 Billing(결제 계정)을 활성화해야 합니다. 이는 Firebase 콘솔의 "프로젝트 설정 > 결제 및 사용량" 메뉴에서 확인 및 설정 가능합니다.
- 위 내용을 따라 진행하시면 문제없이 Firebase 프로젝트와 로컬 환경을 연결하여 Cloud Functions을 배포할 수 있습니다.
'개발활용툴' 카테고리의 다른 글
Perplexity AI 사용하기 - SK텔레콤 고객 이벤트(1년 Pro무료) (2) | 2024.11.27 |
---|---|
무료 아이콘(icon) 활용하기 (1) | 2023.12.29 |
날씨 API - OpenWeather 사용하기(2) (0) | 2023.12.14 |
날씨 API - OpenWeather 사용하기(1) (0) | 2023.12.13 |
Mapbox사용법(5) - Mouse Event (0) | 2023.12.12 |