|
| 1 | +/** |
| 2 | + * Copyright 2017 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +'use strict'; |
| 18 | + |
| 19 | +const functions = require('firebase-functions'); |
| 20 | +const admin = require('firebase-admin'); |
| 21 | +const Language = require('@google-cloud/language'); |
| 22 | +const express = require('express'); |
| 23 | + |
| 24 | +const app = express(); |
| 25 | +const language = new Language({projectId: process.env.GCLOUD_PROJECT}); |
| 26 | + |
| 27 | +admin.initializeApp(functions.config().firebase); |
| 28 | + |
| 29 | +// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header. |
| 30 | +// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this: |
| 31 | +// `Authorization: Bearer <Firebase ID Token>`. |
| 32 | +// when decoded successfully, the ID Token content will be added as `req.user`. |
| 33 | +const authenticate = (req, res, next) => { |
| 34 | + if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) { |
| 35 | + res.status(403).send('Unauthorized'); |
| 36 | + return; |
| 37 | + } |
| 38 | + const idToken = req.headers.authorization.split('Bearer ')[1]; |
| 39 | + admin.auth().verifyIdToken(idToken).then(decodedIdToken => { |
| 40 | + req.user = decodedIdToken; |
| 41 | + next(); |
| 42 | + }).catch(error => { |
| 43 | + res.status(403).send('Unauthorized'); |
| 44 | + }); |
| 45 | +}; |
| 46 | + |
| 47 | +app.use(authenticate); |
| 48 | + |
| 49 | +// POST /api/messages |
| 50 | +// Create a new message, get its sentiment using Google Cloud NLP, |
| 51 | +// and categorize the sentiment before saving. |
| 52 | +app.post('/api/messages', (req, res) => { |
| 53 | + const message = req.body.message; |
| 54 | + |
| 55 | + language.detectSentiment(message).then(results => { |
| 56 | + const category = categorizeScore(results[0].score); |
| 57 | + const data = {message: message, sentiment: results, category: category}; |
| 58 | + return admin.database().ref(`/users/${req.user.uid}/messages`).push(data); |
| 59 | + }).then(snapshot => { |
| 60 | + return snapshot.ref.once('value'); |
| 61 | + }).then(snapshot => { |
| 62 | + const val = snapshot.val(); |
| 63 | + res.status(201).json({message: val.message, category: val.category}); |
| 64 | + }).catch(error => { |
| 65 | + console.log('Error detecting sentiment or saving message', error.message); |
| 66 | + res.sendStatus(500); |
| 67 | + }); |
| 68 | +}); |
| 69 | + |
| 70 | +// GET /api/messages?category={category} |
| 71 | +// Get all messages, optionally specifying a category to filter on |
| 72 | +app.get('/api/messages', (req, res) => { |
| 73 | + const category = req.query.category; |
| 74 | + let query = admin.database().ref(`/users/${req.user.uid}/messages`); |
| 75 | + |
| 76 | + if (category && ['positive', 'negative', 'neutral'].indexOf(category) > -1) { |
| 77 | + // Update the query with the valid category |
| 78 | + query = query.orderByChild('category').equalTo(category); |
| 79 | + } else if (category) { |
| 80 | + return res.status(404).json({errorCode: 404, errorMessage: `category '${category}' not found`}); |
| 81 | + } |
| 82 | + |
| 83 | + query.once('value').then(snapshot => { |
| 84 | + var messages = []; |
| 85 | + snapshot.forEach(childSnapshot => { |
| 86 | + messages.push({key: childSnapshot.key, message: childSnapshot.val().message}); |
| 87 | + }); |
| 88 | + |
| 89 | + return res.status(200).json(messages); |
| 90 | + }).catch(error => { |
| 91 | + console.log('Error getting messages', error.message); |
| 92 | + res.sendStatus(500); |
| 93 | + }); |
| 94 | +}); |
| 95 | + |
| 96 | +// GET /api/message/{messageId} |
| 97 | +// Get details about a message |
| 98 | +app.get('/api/message/:messageId', (req, res) => { |
| 99 | + const messageId = req.params.messageId; |
| 100 | + admin.database().ref(`/users/${req.user.uid}/messages/${messageId}`).once('value').then(snapshot => { |
| 101 | + if (snapshot.val() !== null) { |
| 102 | + // Cache details in the browser for 5 minutes |
| 103 | + res.set('Cache-Control', 'private, max-age=300'); |
| 104 | + res.status(200).json(snapshot.val()); |
| 105 | + } else { |
| 106 | + res.status(404).json({errorCode: 404, errorMessage: `message '${messageId}' not found`}); |
| 107 | + } |
| 108 | + }).catch(error => { |
| 109 | + console.log('Error getting message details', messageId, error.message); |
| 110 | + res.sendStatus(500); |
| 111 | + }); |
| 112 | +}); |
| 113 | + |
| 114 | +// Expose the API as a function |
| 115 | +exports.api = functions.https.onRequest(app); |
| 116 | + |
| 117 | +// Helper function to categorize a sentiment score as positive, negative, or neutral |
| 118 | +const categorizeScore = score => { |
| 119 | + if (score > 0.25) { |
| 120 | + return 'positive'; |
| 121 | + } else if (score < -0.25) { |
| 122 | + return 'negative'; |
| 123 | + } else { |
| 124 | + return 'neutral'; |
| 125 | + } |
| 126 | +} |
0 commit comments