[英]To add a function value into firestore using cloud function
This is the function which returns player name from 3rd party api and i want to store the value which this function is returning into my firestore database(matchList/matchData) as a player name field using cloud function.这是从第 3 方 api 返回玩家名称的函数,我想使用云函数将此函数返回到我的 firestore 数据库(matchList/matchData)中的值存储为玩家名称字段。
var options = {
method: "GET",
hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
port: null,
path: "/scorecards.php?seriesid=2141&matchid=43431",
headers: {
"x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
"x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
},
json: true
};
var req = http.request(options, res => {
var chunks = [];
res.on("data", chunk => {
chunks.push(chunk);
});
res.on("end", () => {
var body = Buffer.concat(chunks);
var json = JSON.parse(body);
playerName = json.fullScorecardAwards.manOfTheMatchName;
console.log("player name", playerName);
response.send(playerName);
});
});
req.end();
}
First download the following:首先下载以下内容:
npm install firebase-admin --save
Then initialize cloud firestore:然后初始化云firestore:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();
Then to store the value do the following:然后存储值执行以下操作:
let docRef = db.collection('match').doc('matchData');
let setPlayer = docRef.set({playerName : playerName});
Check the following for more information:检查以下内容以获取更多信息:
https://firebase.google.com/docs/firestore/quickstart https://firebase.google.com/docs/firestore/quickstart
https://firebase.google.com/docs/functions/get-started https://firebase.google.com/docs/functions/get-started
While it can be argued Firebase/Firestore/Cloud Functions are all part of the same family, the question was how to specifically use Firestore and Cloud Functions under the GCP banner.虽然可以说 Firebase/Firestore/Cloud Functions 都是同一个系列的一部分,但问题是如何在 GCP 的旗帜下专门使用 Firestore 和 Cloud Functions。
From the documentation: https://cloud.google.com/community/tutorials/cloud-functions-firestore从文档: https : //cloud.google.com/community/tutorials/cloud-functions-firestore
const Firestore = require('@google-cloud/firestore');
// Use your project ID here
const PROJECTID = '[YOUR_PROJECT_ID]';
const COLLECTION_NAME = 'cloud-functions-firestore';
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true
// NOTE: Don't hardcode your project credentials here.
// If you have to, export the following to your shell:
// GOOGLE_APPLICATION_CREDENTIALS=<path>
// keyFilename: '/cred/cloud-functions-firestore-000000000000.json',
});
/**
* Retrieve or store a method in Firestore
*
* Responds to any HTTP request.
*
* GET = retrieve
* POST = store (no update)
*
* success: returns the document content in JSON format & status=200
* else: returns an error:<string> & status=404
*
* @param {!express:Request} req HTTP request context.
* @param {!express:Response} res HTTP response context.
*/
exports.main = (req, res) => {
if (req.method === 'POST') {
// store/insert a new document
const data = (req.body) || {};
const ttl = Number.parseInt(data.ttl);
const ciphertext = (data.ciphertext || '')
.replace(/[^a-zA-Z0-9\-_!.,; ']*/g, '')
.trim();
const created = new Date().getTime();
// .add() will automatically assign an ID
return firestore.collection(COLLECTION_NAME).add({
created,
ttl,
ciphertext
}).then(doc => {
console.info('stored new doc id#', doc.id);
return res.status(200).send(doc);
}).catch(err => {
console.error(err);
return res.status(404).send({
error: 'unable to store',
err
});
});
}
// everything below this requires an ID
if (!(req.query && req.query.id)) {
return res.status(404).send({
error: 'No II'
});
}
const id = req.query.id.replace(/[^a-zA-Z0-9]/g, '').trim();
if (!(id && id.length)) {
return res.status(404).send({
error: 'Empty ID'
});
}
if (req.method === 'DELETE') {
// delete an existing document by ID
return firestore.collection(COLLECTION_NAME)
.doc(id)
.delete()
.then(() => {
return res.status(200).send({ status: 'ok' });
}).catch(err => {
console.error(err);
return res.status(404).send({
error: 'unable to delete',
err
});
});
}
// read/retrieve an existing document by ID
return firestore.collection(COLLECTION_NAME)
.doc(id)
.get()
.then(doc => {
if (!(doc && doc.exists)) {
return res.status(404).send({
error: 'Unable to find the document'
});
}
const data = doc.data();
if (!data) {
return res.status(404).send({
error: 'Found document is empty'
});
}
return res.status(200).send(data);
}).catch(err => {
console.error(err);
return res.status(404).send({
error: 'Unable to retrieve the document',
err
});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.