-
functions에서 database 접근하기카테고리 없음 2023. 10. 17. 20:16반응형
구글
realtime database 문서 검색
firebase 문서 > 실시간 데이터베이스 > 관리 > 시작하기
관리자 권한으로 인증 - node.js - 코드 샘플 복사
이 코드들은 프론트엔드에서 사용한 아래의 코드들을 대신하는 것
const firebaseConfig = { apiKey: "AIzaSyCQk_0gmB2f6avo5FcW1J6nF7GlDnt2TOo", authDomain: "test-database100.firebaseapp.com", databaseURL: "https://test-database100-default-rtdb.firebaseio.com", projectId: "test-database100", storageBucket: "test-database100.appspot.com", messagingSenderId: "998427758923", appId: "1:998427758923:web:1484ed68cb4961320898ce" };
비쥬얼스튜디오
index.js 파일에 붙여넣기
/** * Import function triggers from their respective submodules: * * const {onCall} = require("firebase-functions/v2/https"); * const {onDocumentWritten} = require("firebase-functions/v2/firestore"); * * See a full list of supported triggers at https://firebase.google.com/docs/functions */ const { onRequest } = require("firebase-functions/v2/https"); const logger = require("firebase-functions/logger"); // Create and deploy your first functions // https://firebase.google.com/docs/functions/get-started // node.js - 백엔드 const functions = require("firebase-admin"); let admin = require("firebase-admin"); // Fetch the service account key JSON file contents let serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a service account, granting admin privileges admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules let db = admin.database(); let ref = db.ref("restricted_access/secret_document"); ref.once("value", function(snapshot) { console.log(snapshot.val()); }); exports.helloWorld = onRequest((request, response) => { // logger.info("Hello logs!", {structuredData: true}); response.send("Hello from Firebase!"); }); exports.ceocamp = onRequest((request, response) => { let byul ={ name : "이한별", age : 33, height : 176 } response.send(byul); });
var admin = require("firebase-admin"); // Fetch the service account key JSON file contents var serviceAccount = require("path/to/serviceAccountKey.json"); // Initialize the app with a service account, granting admin privileges admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules var db = admin.database(); var ref = db.ref("restricted_access/secret_document"); ref.once("value", function(snapshot) { console.log(snapshot.val()); });
단, 여기서 serviceAccountKey와 DATABASE_NAME은 나의 고유값으로 바꿔야 한다
고유값 찾기
firebase
프로젝트 개요
프로젝트 설정
서비스 계정
node.js
코드 복사
비쥬얼스튜디오
// Initialize the app with a service account, granting admin privileges admin.initializeApp({ credential: admin.credential.cert(serviceAccount), // The database URL depends on the location of the database databaseURL: "https://DATABASE_NAME.firebaseio.com" });
->
admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test-database100-default-rtdb.firebaseio.com" });
firebase
새 비공개 키 생성
키 생성(json 파일이 다운로드 된다)
파일 열기
키 값들이 들어있다
이 파일을 해당 폴더의 functions 폴더에 넣어주기
파일 이름 복사
비쥬얼스튜디오
index.js
let serviceAccount = require("path/to/serviceAccountKey.json");
->
let serviceAccount = require("test-database100-firebase-adminsdk-o6kef-ca7582428c.json");
단, 동일한 경로(functions -> index.js)인것을 알리기 위해 "./"를 앞에 넣어준다
let serviceAccount = require("./test-database100-firebase-adminsdk-o6kef-ca7582428c.json");
만약 다운로드 폴더 안에 있다면 아래 처럼 표시
let serviceAccount = require("/downloads/test-database100-firebase-adminsdk-o6kef-ca7582428c.json");
realtime database 가져오기
비쥬얼스튜디오
exports.helloWorld = onRequest((request, response) => { db.ref("testtest").set("functions 이용해서 database에 값 넣기"); // db.ref("키값").set("벨류값"); response.send("Hello from Firebase!"); });
여기까지의 최종 코드
/** * Import function triggers from their respective submodules: * * const {onCall} = require("firebase-functions/v2/https"); * const {onDocumentWritten} = require("firebase-functions/v2/firestore"); * * See a full list of supported triggers at https://firebase.google.com/docs/functions */ const { onRequest } = require("firebase-functions/v2/https"); const logger = require("firebase-functions/logger"); // Create and deploy your first functions // https://firebase.google.com/docs/functions/get-started // node.js - 백엔드 const functions = require("firebase-admin"); let admin = require("firebase-admin"); // Fetch the service account key JSON file contents let serviceAccount = require("./test-database100-firebase-adminsdk-o6kef-ca7582428c.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test-database100-default-rtdb.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules let db = admin.database(); exports.helloWorld = functions.https.onRequest((request, response) => { db.ref("testtest").set("functions 이용해서 database에 값 넣기"); response.send("Hello from Firebase!"); }); exports.ceocamp = functions.https.onRequest((request, response) => { let byul = { name: "이한별", age: 33, height: 176 } response.send(byul); });
터미널
해당 폴더 들어가기(testdatabase)
firebase deploy