From 6196f534bca2b9e96c72aeb8c8337b5975225472 Mon Sep 17 00:00:00 2001 From: Ollie Silviotti Date: Tue, 29 Dec 2020 02:17:51 +0000 Subject: [PATCH] Add simple querying --- gatsby-node.js | 49 ++++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/gatsby-node.js b/gatsby-node.js index 6bfe631..7060a20 100755 --- a/gatsby-node.js +++ b/gatsby-node.js @@ -1,24 +1,20 @@ -const report = require('gatsby-cli/lib/reporter'); -const firebase = require('firebase-admin'); -const crypto = require('crypto'); - -const getDigest = id => - crypto - .createHash('md5') - .update(id) - .digest('hex'); - -exports.sourceNodes = async ( - { actions }, - { types, credential } -) => { - - try{ +const report = require("gatsby-cli/lib/reporter"); +const firebase = require("firebase-admin"); +const crypto = require("crypto"); + +const getDigest = (id) => crypto.createHash("md5").update(id).digest("hex"); + +exports.sourceNodes = async ({ actions }, { types, credential }) => { + try { if (firebase.apps || !firebase.apps.length) { - firebase.initializeApp({ credential: firebase.credential.cert(credential) }); + firebase.initializeApp({ + credential: firebase.credential.cert(credential), + }); } } catch (e) { - report.warn('Could not initialize Firebase. Please check `credential` property in gatsby-config.js'); + report.warn( + "Could not initialize Firebase. Please check `credential` property in gatsby-config.js" + ); report.warn(e); return; } @@ -28,8 +24,8 @@ exports.sourceNodes = async ( const { createNode } = actions; const promises = types.map( - async ({ collection, type, map = node => node }) => { - const snapshot = await db.collection(collection).get(); + async ({ collection, type, map = (node) => node, query }) => { + const snapshot = await queryDb(db, collection, query); for (let doc of snapshot.docs) { const contentDigest = getDigest(doc.id); createNode( @@ -52,4 +48,15 @@ exports.sourceNodes = async ( await Promise.all(promises); return; -}; \ No newline at end of file +}; + +function queryDb(db, collection, query) { + let dbQuery = db.collection(collection); + + if (query?.where) { + const { field, comparator, value } = query.where; + dbQuery = dbQuery.where(field, comparator, value); + } + + return dbQuery.get(); +}