Skip to content

Instantly share code, notes, and snippets.

@jshakes
Last active January 12, 2021 20:16
Show Gist options
  • Save jshakes/bab2615eb2b4e6e5fd662df59141d4f7 to your computer and use it in GitHub Desktop.
Save jshakes/bab2615eb2b4e6e5fd662df59141d4f7 to your computer and use it in GitHub Desktop.
Cloud functions examples for Tatsuya
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Mercury = require('@postlight/mercury-parser');
const { countArticleWords } = require( './lib/articles' );
admin.initializeApp(functions.config().firebase);
/*
Create some profile information in the users collection,
including an array in which to store the user's article
IDs and any other profile information
Todo: delete this information on user account removal
*/
exports.createProfile = functions.auth.user()
.onCreate(user => (
// Include the Welcome message in the user's article list
admin.database().ref(`users/${user.uid}`).set({
articles: [
{
articleId: 'welcome',
read: false,
deleted: false,
scrollDepth: 0,
dateAdded: Date.now(),
},
],
})
));
exports.fetchArticleData = functions.database.ref('/articles/{articleId}')
.onCreate(snapshot => {
const article = snapshot.val();
const { url } = article;
console.log('New URL added. Fetching data for', url);
return Mercury.parse(url)
.then(data => {
console.log('Received data', data);
let { word_count } = data;
const { content } = data;
/*
If word_count is too low, Mercury probably failed to return
a usable value. Attempt our own rudimentary word count by
stripping the HTML tags and counting the spaces.
*/
if ( word_count < 10 && content.length ) {
word_count = countArticleWords( content );
}
snapshot.ref.update( {
...data,
word_count,
} );
})
.catch(err => {
console.error('Could not fetch data for', url, err);
snapshot.ref.update({
error: true,
});
});
});
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"engines": {
"node": "8"
},
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"@postlight/mercury-parser": "^2.0.0",
"firebase-admin": "~7.0.0",
"firebase-functions": "^2.2.0"
},
"private": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment