본문 바로가기

programming/db, web, node.js

firebase webapp 개발 - 03. real-time database get, set

아래와 같이 index.js에 database get 코드를 삽입한다.

 

...

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getDatabase, ref, child, get } from "firebase/database";

...

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

const db = getDatabase()
const dbRef = ref(db);
test(dbRef);

async function test(dbRef)
{
	const dbBook = child(dbRef, 'book-contents/default');
	await testGet(dbBook)
	testSet(dbBook)
}

function testGet(dbBook)
{
	const dbNames = child(dbBook, 'voca-names');
	return get(dbNames).then((snapshot) => {
		if (snapshot.exists()) {
			console.log(snapshot.val());
		} else {
			console.log("No data available");
		}
	}).catch((error) => {
		console.error(error);
	});
}


function testSet(dbBook)
{
	const refName = child(dbBook, 'voca-names/2');
	return set(refName, "cloth");
}

 

webpack을 다시 실행한 후, server를 재가동한다.

npx webpack

 

firebase serve --only hosting

 

get 결과로 아래와 같이 console 출력되면 정상이다.

['calendar', 'time']

 

set 결과로 voca-names에 "cloth"가 추가되면 정상이다.