我试图查看我的代码出了什么问题。现在,我有一个Cloud Firestore函数,该函数使用request-promise-native和Cheerio来从网页中获取一些数据并将其写入到我的firestore数据库中。
奇怪的是,当我在请求运行之前第一次向数据库中手动添加文档时,我的代码有效。
//var setDoc = scheduleRef.add({"hi": "hello world"});
如果未注释此行,则它将及其下面的所有代码正常工作,并根据需要在Cheerio .each方法中将我的对象写入数据库。
为什么在进入网络抓取循环之前手动添加文档会使所有代码正常工作?为什么它不起作用?谁能向我解释一下?
谢谢
import * as functions from 'firebase-functions';
import * as cheerio from 'cheerio';
import * as moment from 'moment';
import * as admin from 'firebase-admin';
import * as request from "request-promise-native";
admin.initializeApp(functions.config().firebase);
const urlDate = moment().format('YYYYMMDD');
const database = admin.firestore();
export const getnewPlayers = functions.https.onRequest((req, response) => {
const scheduleRef = database.collection('NBASchedule');
//var setDoc = scheduleRef.add({"hi": "hello world"});
const options = {
uri: 'https://www.cbssports.com/nba/scoreboard/',
transform: function (body) {
return cheerio.load(body);
}
};
request(options)
.then(($) => {
$('.live-update').each( (i, element) => {
const homeTeamAbbr = $(element).find('tbody').children('tr').eq(0).find('a').html().split("alt/").pop().split('.svg')[0];
const awayTeamAbbr = $(element).find('tbody').children('tr').eq(1).find('a').html().split("alt/").pop().split('.svg')[0];
const homeTeam = $(element).find('tbody').children('tr').eq(0).find('a.team').text().trim();
const awayTeam = $(element).find('tbody').children('tr').eq(1).find('a.team').text().trim();
var homeTeamStatsURL = $(element).find('tbody').children('tr').eq(0).find('td').html();
var awayTeamStatsURL = $(element).find('tbody').children('tr').eq(1).find('td').html();
const gameTime = $(element).find('.pregame-date').text().trim();
homeTeamStatsURL = homeTeamStatsURL.match(/href="([^"]*)/)[1] + "roster";
awayTeamStatsURL = awayTeamStatsURL.match(/href="([^"]*)/)[1] + "roster";
const matchupString = awayTeamAbbr + "@" + homeTeamAbbr;
const URLString = "NBA_" + urlDate + "_" + matchupString;
var boxScoreURL = "www.cbssports.com/nba/gametracker/boxscore/" + URLString;
const setScheule = scheduleRef.doc(URLString).set({
homeTeam: homeTeam,
awayTeam: awayTeam,
date: gameTime,
homeTeamAbbr: homeTeamAbbr,
awayTeamAbbr: awayTeamAbbr,
homeTeamStatsURL: homeTeamStatsURL,
awayTeamStatsURL: awayTeamStatsURL,
boxScoreURL: boxScoreURL
});
setScheule.then(writeResult => {
console.log("retrieved schedule for "+ matchupString + " on " + urlDate);
return 0;
});
//getTeamPlayers(homeTeamStatsURL, matchupString);
// getTeamPlayers(awayTeamStatsURL, matchupString);
});
response.send("retrieved schedule");
})
.catch(function (err) {
console.log("error " + err);
});
});