「Gcp/Firebase/Firestore/async」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→dbのsum) |
|||
(同じ利用者による、間の3版が非表示) | |||
行1: | 行1: | ||
− | + | ==通常のfirestore取得をasync/awaitに変更する方法== | |
+ | functionにasyncを追加し、firestoreのget()にawaitを追加すればよい。 | ||
− | == | + | ==async/awaitを使わないfirestoreのサンプル== |
+ | <pre> | ||
const functions = require('firebase-functions'); | const functions = require('firebase-functions'); | ||
const admin = require('firebase-admin'); | const admin = require('firebase-admin'); | ||
行19: | 行21: | ||
}); | }); | ||
}); | }); | ||
+ | </pre> | ||
+ | |||
+ | ==async/awaitを使うfirestoreのサンプル== | ||
+ | <pre> | ||
+ | exports.dbasync = functions | ||
+ | .region('asia-northeast1') | ||
+ | .https.onRequest(async(request, response) => { | ||
+ | var snapshot = await admin.firestore().collection('scores') | ||
+ | .orderBy('maxKanaSpeed', 'desc') | ||
+ | .limit(50) | ||
+ | .get(); | ||
+ | var scores = snapshot.docs.map(x => x.data()); | ||
+ | var json = JSON.stringify(scores); | ||
+ | response.send("json" + json); | ||
+ | }); | ||
+ | </pre> | ||
+ | |||
+ | ==dbのsum== | ||
+ | <pre> | ||
+ | exports.helloWorld = functions | ||
+ | .region('asia-northeast1') | ||
+ | .https.onRequest(async(request, response) => { | ||
+ | const count = 50; | ||
+ | var snapshot = await admin.firestore().collection('users') | ||
+ | .orderBy('age', 'desc') | ||
+ | .limit(count) | ||
+ | .get(); | ||
+ | const sum = snapshot.docs | ||
+ | .map(doc => doc.data().age) | ||
+ | .reduce((prev, current) => prev + current, 0); | ||
+ | console.log( "sum=" + sum.toString() ); | ||
+ | }); | ||
+ | </pre> |
2020年3月6日 (金) 01:25時点における最新版
目次
通常のfirestore取得をasync/awaitに変更する方法
functionにasyncを追加し、firestoreのget()にawaitを追加すればよい。
async/awaitを使わないfirestoreのサンプル
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.db = functions .region('asia-northeast1') .https.onRequest((request, response) => { admin.firestore().collection('scores') .orderBy('maxKanaSpeed', 'desc') .limit(50) .get() .then((snapshot) => { var scores = snapshot.docs.map(x => x.data()); var json = JSON.stringify(scores); response.send("json" + json); }); });
async/awaitを使うfirestoreのサンプル
exports.dbasync = functions .region('asia-northeast1') .https.onRequest(async(request, response) => { var snapshot = await admin.firestore().collection('scores') .orderBy('maxKanaSpeed', 'desc') .limit(50) .get(); var scores = snapshot.docs.map(x => x.data()); var json = JSON.stringify(scores); response.send("json" + json); });
dbのsum
exports.helloWorld = functions .region('asia-northeast1') .https.onRequest(async(request, response) => { const count = 50; var snapshot = await admin.firestore().collection('users') .orderBy('age', 'desc') .limit(count) .get(); const sum = snapshot.docs .map(doc => doc.data().age) .reduce((prev, current) => prev + current, 0); console.log( "sum=" + sum.toString() ); });