Skip to content

Instantly share code, notes, and snippets.

@ernestkamara
Last active March 10, 2020 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ernestkamara/8a36117c189fa0fbd4822fa503c8977d to your computer and use it in GitHub Desktop.
Save ernestkamara/8a36117c189fa0fbd4822fa503c8977d to your computer and use it in GitHub Desktop.
Cloud Functions Demo
// functions/index.js
const admin = require('firebase-admin');
const functions = require('firebase-functions');
// path to a service account key JSON file
const serviceAccount = require("./account_key.json");
// Lightweight JavaScript date library for parsing, validating,
// manipulating, and formatting dates.
const moment = require('moment');
// Serpwow module
const SerpWow = require('google-search-results-serpwow');
// create the serpwow object, passing in our API key
const serpwow = new SerpWow(API_KEY');
// Initialize the default app
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://APP_ID.firebaseio.com"
});
// minimum time period(i.e. 'from') search parameter
const min_date = moment().subtract(1, 'days').format("MM/DD/YYYY");
// maximum time period(i.e. 'to') search parameter
const max_date = moment().format("MM/DD/YYYY");
// set up the search parameters,
const params = {
q: 'freetown',
search_type: 'news',
news_type: 'all',
num: '10',
time_period: 'custom',
sort_by: 'date',
time_period_min: min_date,
time_period_max: max_date
};
// The function scheduled to run every 12 hours
exports.scheduledFunction = functions.pubsub.schedule('every 12 hours').onRun(async (context) => {
// retrieve the search results as JSON
await serpwow.json(params)
.then(result => {
// Articles Firestore CollectionReference
const articlesRef = admin.firestore().collection('articles');
// Save search results to Firestore
const articles = result["news_results"]
articles.forEach(article => {
const id = article['date_utc'] + article['position']
articlesRef
.doc(id)
.set(article)
.catch(error => {
console.log(error);
})
});
})
.catch(error => {
console.log(error);
});
return null;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment