저는 Reactjs에 api에서 데이터 (숫자)를 가져오고 사용자가 페이지를 열면이 숫자를 Firebase 컬렉션의 숫자와 더해 사용자가이 숫자를 볼 수있는 스크립트가 있습니다. 앱에는 많은 사용자가있을 것이고 모든 사용자는 동일한 스크립트에서 다른 숫자를 갖게 될 것입니다.
Firebase Cloud Functions로 서버에서이 클라이언트 측 스크립트를 실행하고 서버에서이 번호를 호출하고이 번호를 Firestore 컬렉션에 저장할 수 있는지 궁금합니다.
im nodejs 및 클라우드 기능의 초보자입니다. 이것이 가능한지 모르겠습니다.
API에서 숫자를 얻다
getLatestNum = (sym) => {
return API.getMarketBatch(sym).then((data) => {
return data;
});
};
내가 시도한 클라우드 기능
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub
.schedule('30 20 * * *')
.onRun((context) => {
const appointmentTimesCollectionRef = db.collection('data');
return appointmentTimesCollectionRef
.get()
.then((querySnapshot) => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.batch();
querySnapshot.forEach((doc) => {
console.log(doc);
});
return batch.commit();
}
})
.catch((error) => {
console.log(error);
return null;
});
});
실제로 Cloud 함수에서 REST API를 호출 할 수 있습니다. axios 와 같이 Promise를 반환하는 Node.js 라이브러리를 사용해야합니다 .
귀하의 질문에서 작성하려는 특정 Firestore 문서에 대해 100 % 명확하지는 않지만 일괄 쓰기 내에서 수행 될 것이라고 가정합니다.
따라서 다음 줄을 따라 수행해야합니다.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub
.schedule('30 20 * * *')
.onRun((context) => {
let apiData;
return axios.get('https://yourapiuri...')
.then(response => {
apiData = response.data; //For example, it depends on what the API returns
const appointmentTimesCollectionRef = db.collection('data');
return appointmentTimesCollectionRef.get();
})
.then((querySnapshot) => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.batch();
querySnapshot.forEach((doc) => {
batch.update(doc.ref, { fieldApiData: apiData});
});
return batch.commit();
}
})
.catch((error) => {
console.log(error);
return null;
});
});
주의해야 할 두 가지 사항 :
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다