FireBase

류지승·2024년 10월 18일

Database

목록 보기
4/9
post-thumbnail

백엔드 없이 데이터 저장을 가능하게 하는 것을 BaaS(Backend as a Service) 라고한다. FireBaseBaaS이다. FireBase는 realtime database(nosql + 실시간 통신) / firestore(nosql) 일반적으로 firestore를 주로 사용한다.

FireBase 공식 홈페이지

setting은 블로그 및 유튜브 영상 참고

FireBase 사용해보기

firebase 관련 config를 받게 되는데 다음과 같다.

/** @format */

import { initializeApp } from 'firebase/app';

const firebaseConfig = {
	apiKey: '******',
	authDomain: '***************',
	projectId: '***********',
	storageBucket: '*******',
	messagingSenderId: '************',
	appId: '****************',
};

// Initialize Firebase
export const firebaseApp = initializeApp(firebaseConfig);

이런 형식으로 코드를 받는데, 그냥 config하고 초기화 시켜주면 firebase를 사용할 수 있다.

/** @format */
'use client'

import { addDoc, collection, getDocs, getFirestore } from 'firebase/firestore'

import { firebaseApp } from '@/lib/firebase_config'

export default function page() {
	const onClickSumbit = async () => {
		const board = collection(getFirestore(firebaseApp), 'board')
		await addDoc(board, {
			writer: '123',
			title: '123',
			contents: '123',
		})
	}
	const onClickFetch = async () => {
		const board = collection(getFirestore(firebaseApp), 'board')
		const result = await getDocs(board)
		const datas = result.docs.map((el) => el.data())
		console.log(datas)
	}

	return (
		<>
			<button onClick={onClickSumbit}>등록</button>
			<button onClick={onClickFetch}>조회</button>
		</>
	)
}

firebase 문법 정리
getFirestore - config에서 정의한 객체를 가지고 Firebase 앱과 연결된 Firestore 데이터베이스를 초기화하고, 애플리케이션에서 데이터베이스에 접근할 수 있도록 해준다.
collection - Firebase에서 두 번째 인자로 받는 collection 을 참조할 수 있도록 하는 객체를 반환한다. 해당 객체는 collection 내의 document에 접근하거나 데이터 작업(읽기, 쓰기, 업데이트, 삭제 등)을 수행할 수 있다.
doc - 특정 collectiondocument를 참조하는 객체를 반환한다. 다음과 같은 형태로 특정 collectiondocument를 들고온다.

  • doc(db, collection, document)

addDoc - collection으로 들고온 객체에 새로운 document를 추가하는 역할을 한다.
getDocs - collection 내의 모든 document를 가져오는 역할을 한다.
getDoc - collection 내의 특정 document를 가져오는 역할을 한다. document의 ID를 이용하여 참조할 수 있다.
updateDoc - 기존 document를 update하는 함수다. document의 특정 field를 수정하거나 추가할 수 있다.
deleteDoc - 특정 document를 삭제하는 함수다.

setDoc - document를 특정 ID로 생성하거나 기존 document를 덮어씌우는 함수다. updateDoc와 차이라고 하면 우리가 아는 method 중에 Put과 Patch 차이라고 보면 된다. 즉, updateDocpatch과 같은 일부만, 수정하기 위해서 사용하고 `setDoc는 put과 같이 전체 수정할 때 사용한다.

onSnapshot - 실시간 업데이트를 구독하여 데이터의 변경 사항을 실시간으로 반영할 수 있다. 우리가 흔히 아는 webSocket이라고 생각하면 이해하기가 편하다.
query & where - query를 이용하여 document에 있는 field와 조건이 맞는 데이터만 필터링할 수 있다. query에서 두 번째 인자로 where무을 사용할 수 있다 예시 -> query(collection(db, 'users'), where('age', '>=', 18));

생각했던 것보다 너무 좋은 cloud storage 같다 왜냐? 백엔드에서 해야하는 기능들이 다 있기 때문이다. 생각보다 세세하다. auth부터 시작해서 transaction, query, 실시간 통신, 정렬, limit . client 딴에서 test용도로 해야한다면 난 강력하게 firebase를 사용할 것이다. 비용이 꽤나 부담된다면 MSW & FireBase 조합을 이용하여 api 통신 테스트를 할 것이다. 다음에 기회가 되면 firebase를 제대로 사용해보곤 싶다. 현실적으로 nest를 공부하고 있기 때문에 사용할 일은 없을 듯?

profile
성실(誠實)한 사람만이 목표를 성실(成實)한다

0개의 댓글