반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- 개발
- androidstudio
- build
- MachineLearning
- 맥
- IOS
- TensorFlow
- linux
- jest
- ReactNative
- Android
- PYTHON
- node
- 센토스
- webpack
- 네트워크
- react
- vsCode
- VirtualBox
- xcode
- qunit
- MAC
- unittest
- centos
- avds
- picker
- Chrome
- localserver
- 리눅스
Archives
- Today
- Total
로메오의 블로그
[Firebase] FireStore 사용하기 - jQuery용 본문
반응형
파일 설정
$ 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
반응형
'Frontend > Firebase' 카테고리의 다른 글
firebase functions 설정 (0) | 2024.05.19 |
---|---|
[Firebase] Firebase Auth 사용하기 - jQuery용 (0) | 2023.02.17 |
[Firebase] Dynamic Links 설정 (0) | 2022.12.16 |
[Firebase] GCP 리소스 위치 (2) | 2020.05.14 |
[Firebase] 도메인 연결 - Cafe24 서브도메인 연결하기 (3) | 2020.02.06 |
Comments