로메오의 블로그

[Firebase] FireStore 사용하기 - jQuery용 본문

Frontend/Firebase

[Firebase] FireStore 사용하기 - jQuery용

romeoh 2023. 2. 16. 15:45
반응형

Firebase 목록

React 목록

파일 설정

$ mkdir firebase
$ cd firebase
$ mkdir public
$ mkdir public/js
$ touch public/js/firebase.js
$ touch public/index.html
$ touch App.js

 

 

Node 서버 구성

App.js

$ npm install express
const express = require('express')
const app = express();
const port = 3001;

app.use(express.static('public'));
app.get('', (req, res) => {
    res.sendFile(__dirname + '/index.html')
})

app.listen(port, () => {
    console.log('Example app port: ' + port);
})

 

 

 

프론트 

index.html

<!doctype html>
<html lang="ko">
<head>
    <meta charset="utf-8">
    <title>깨유</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css"/>
</head>

<body>
    <button class="btn btn-primary" id="btnDocumentsCount">문서갯수</button>
    <button class="btn btn-primary" id="btnQuery">쿼리조회</button>
    <button class="btn btn-primary" id="btnAddDocument">문서추가</button>
    <button class="btn btn-primary" id="btnSetDocument">문서 병합</button>
    <button class="btn btn-primary" id="btnUpdateDocument">문서 업데이트</button>
    <button class="btn btn-primary" id="btnDeleteField">필드 삭제</button>
    <button class="btn btn-primary" id="btnDeleteDocument">문서 삭제</button>

    <div id="collections"></div>
    <hr />
    <div id="documents"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"></script>
    <script type="module" src="./js/firebase.js"></script>
</body>
</html>

 

 

js/firebase.js

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js'
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-analytics.js"
import { getAuth } from 'https://www.gstatic.com/firebasejs/9.17.1/firebase-auth.js'
import { 
  getFirestore, 
  getDocs, 
  getDoc,
  collection,
  getCountFromServer, 
  query,
  where,
  addDoc,
  setDoc,
  deleteDoc,
  doc,
  updateDoc,
  deleteField,
  onSnapshot,
} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-firestore.js"

class Gaeyou {
  
  constructor() {
    this.firebaseInit()
    this.init()
    this.eventInit()
    this.getCollections()
    this.getSubCollection()
    this.watchCollection()
  }

  /**
   * Firebase 설정
   */
  firebaseInit() {
    const firebaseConfig = {
      apiKey: "[]",
      authDomain: "[]",
      projectId: "[]",
      storageBucket: "[]",
      messagingSenderId: "[]",
      appId: "[]",
      measurementId: "[]"
    }
    const app = initializeApp(firebaseConfig)
    getAnalytics(app)
    this.db = getFirestore(app)
    this.nationCollection = collection(this.db, 'nation')
  }

  /**
   * 초기화
   */
  init() {
    this.$collections       = $('#collections')
    this.$documents         = $('#documents')
    this.$btnDocumentsCount = $('#btnDocumentsCount')
    this.$btnQuery          = $('#btnQuery')
    this.$btnAddDocument    = $('#btnAddDocument')
    this.$btnSetDocument    = $('#btnSetDocument')
    this.$btnUpdateDocument = $('#btnUpdateDocument')
    this.$btnDeleteField    = $('#btnDeleteField')
    this.$btnDeleteDocument = $('#btnDeleteDocument')

    this.documentId         = null
  }

  /**
   * 이벤트 할당
   */
  eventInit() {
    this.$btnDocumentsCount.on('click', this.getDocumentsCount.bind(this))
    this.$btnQuery.on('click'         , this.getQuery.bind(this))
    this.$btnAddDocument.on('click'   , this.addDocument.bind(this))
    this.$btnSetDocument.on('click'   , this.setDocument.bind(this))
    this.$btnUpdateDocument.on('click', this.updateDocument.bind(this))
    this.$btnDeleteField.on('click'   , this.deleteField.bind(this))
    this.$btnDeleteDocument.on('click', this.deleteDocument.bind(this))
  }

  /**
   * 컬랙션 모두 가져오기
   */
  async getCollections() {
    const snapshot = await getDocs(this.nationCollection)
    const cityList = snapshot.docs.map(doc => doc.data())
    this.$collections.html(JSON.stringify(cityList))
  }
  
  /**
   * 문서갯수 가져오기
   */
  async getDocumentsCount() {
    const snapshot = await getCountFromServer(this.nationCollection)
    const count = snapshot.data().count
    console.log(count)
  }

  /**
   * 쿼리 조회
   */
  async getQuery() {
    const queryString = query(
      this.nationCollection,
      where ('name', '==', 'Korea')
    );
    const snapshot = await getCountFromServer(queryString)
    const queryCount = snapshot.data().count
    console.log(queryCount)
  }

  /**
   * 문서추가
   */
  async addDocument() {
    try {
      const docRef = await addDoc(this.nationCollection, {
        name: 'Japan',
        capital: 'Tokyo'
      })
      this.documentId = docRef.id
      this.watchDocument()
      console.log(this.documentId)
    } catch(e) {
      console.error('error: ', e)
    }
  }

  /**
   * 문서 업데이트
   */
  async setDocument() {
    if (!this.documentId) return;
    try {
      const docRef = doc(this.db, 'nation', this.documentId)
      await setDoc(docRef, {
        company: 'Sony'
      }, {merge: true})
    } catch(e) {
      console.error('error: ', e)
    }
  }

  /**
   * 문서 업데이트
   */
  async updateDocument() {
    updateDoc(doc(this.db, 'nation', this.documentId), {
      company: 'Honda'
    })
  }

  /**
   * 필드 삭제
   */
  async deleteField() {
    await updateDoc(doc(this.db, 'nation', this.documentId), {
      company: deleteField()
    })
  }

  /**
   * 문서 삭제
   */
  async deleteDocument() {
    await deleteDoc(doc(this.db, 'nation', this.documentId))
    this.documentId = null
    this.$documents.html('')
  }

  /**
   * 컬랙션 실시간 업데이트
   */
  watchCollection() {
    const collectionRef = collection(this.db, 'nation')
    const onSub = onSnapshot(collectionRef, (snapshot) => {
      const nationList = snapshot.docs.map(doc => doc.data())
      this.$collections.html(JSON.stringify(nationList))
    })
  }

  /**
   * 문서 실시간 업데이트
   */
  watchDocument() {
    const docRef = doc(this.db, 'nation', this.documentId)
    const onSub = onSnapshot(docRef, (doc) => {
      this.$documents.html(JSON.stringify(doc.data()))
      console.log(doc.data());
    })

  /**
   * 서브 컬랙션 가져오기
   */
  async getSubCollection() {
    const docRef = doc(this.db, 'nation', 'QUUWqI2LejXIb1n5X5jX')
    const chatCol = collection(docRef, 'cities');
    const citySnapshot = await getDocs(chatCol);
    const cityList = citySnapshot.docs.map(doc => doc.data());
    console.log(cityList)
  }
  
}

document.addEventListener('DOMContentLoaded', () => {
  window.gaeyou = new Gaeyou();
});

 

 

 

서버구동

$ node App
Example app port: 3001

 

 

 

 

Firebase 목록

React 목록

반응형
Comments