Skip to content

Commit 41774c2

Browse files
authored
Update index.js
1 parent a6ea53b commit 41774c2

File tree

1 file changed

+43
-37
lines changed
  • firestore/full-text-search/functions

1 file changed

+43
-37
lines changed
Lines changed: 43 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1-
const functions = require("firebase-functions");
2-
const firestore = require("firebase-functions/lib/providers/firestore");
3-
const Firestore = require("@google-cloud/firestore");
4-
5-
const algoliasearch = require("algoliasearch");
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+
const functions = require('firebase-functions');
17+
const algoliasearch = require('algoliasearch');
618

719
// [START init_algolia]
820
// Initialize Algolia, requires installing Algolia dependencies:
@@ -11,25 +23,20 @@ const algoliasearch = require("algoliasearch");
1123
// App ID and API Key are stored in functions config variables
1224
const ALGOLIA_ID = functions.config().algolia.app_id;
1325
const ALGOLIA_ADMIN_KEY = functions.config().algolia.api_key;
26+
const ALGOLIA_SEARCH_KEY = functions.config().algolia.search_key;
1427

15-
const ALGOLIA_INDEX_NAME = "notes";
28+
const ALGOLIA_INDEX_NAME = 'notes';
1629
const client = algoliasearch(ALGOLIA_ID, ALGOLIA_ADMIN_KEY);
1730
// [END init_algolia]
1831

19-
// Initialize Firestore
20-
const firestoreOptions = {
21-
projectId: process.env.GCLOUD_PROJECT
22-
};
23-
const db = new Firestore(firestoreOptions);
24-
2532
// [START update_index_function]
2633
// Update the search index every time a blog post is written.
27-
exports.onNoteCreated = firestore.document("notes/{noteId}").onCreate(event => {
34+
exports.onNoteCreated = functions.firestore.document('notes/{noteId}').onCreate(event => {
2835
// Get the note document
2936
const note = event.data.data();
3037

31-
// Add an "objectID" field which Algolia requires
32-
note.objectID = event.params.postId;
38+
// Add an 'objectID' field which Algolia requires
39+
note.objectID = event.params.noteId;
3340

3441
// Write to the algolia index
3542
const index = client.initIndex(ALGOLIA_INDEX_NAME);
@@ -38,65 +45,64 @@ exports.onNoteCreated = firestore.document("notes/{noteId}").onCreate(event => {
3845
// [END update_index_function]
3946

4047
// [START get_firebase_user]
41-
const admin = require("admin");
48+
const admin = require('firebase-admin');
49+
admin.initializeApp(functions.config().firebase);
4250

4351
function getFirebaseUser(req, res, next) {
44-
console.log("Check if request is authorized with Firebase ID token");
52+
console.log('Check if request is authorized with Firebase ID token');
4553

46-
if (
47-
!req.headers.authorization ||
48-
!req.headers.authorization.startsWith("Bearer ")
49-
) {
54+
if (!req.headers.authorization
55+
|| !req.headers.authorization.startsWith('Bearer ')) {
5056
console.error(
51-
"No Firebase ID token was passed as a Bearer token in the Authorization header.",
52-
"Make sure you authorize your request by providing the following HTTP header:",
53-
"Authorization: Bearer <Firebase ID Token>"
57+
'No Firebase ID token was passed as a Bearer token in the Authorization header.',
58+
'Make sure you authorize your request by providing the following HTTP header:',
59+
'Authorization: Bearer <Firebase ID Token>'
5460
);
55-
res.status(403).send("Unauthorized");
61+
res.status(403).send('Unauthorized');
5662
return;
5763
}
5864

5965
let idToken;
6066
if (
6167
req.headers.authorization &&
62-
req.headers.authorization.startsWith("Bearer ")
68+
req.headers.authorization.startsWith('Bearer ')
6369
) {
64-
console.log("Found 'Authorization' header");
65-
idToken = req.headers.authorization.split("Bearer ")[1];
70+
console.log('Found 'Authorization' header');
71+
idToken = req.headers.authorization.split('Bearer ')[1];
6672
}
6773

6874
admin
6975
.auth()
7076
.verifyIdToken(idToken)
7177
.then(decodedIdToken => {
72-
console.log("ID Token correctly decoded", decodedIdToken);
78+
console.log('ID Token correctly decoded', decodedIdToken);
7379
req.user = decodedIdToken;
7480
next();
7581
})
7682
.catch(error => {
77-
console.error("Error while verifying Firebase ID token:", error);
78-
res.status(403).send("Unauthorized");
83+
console.error('Error while verifying Firebase ID token:', error);
84+
res.status(403).send('Unauthorized');
7985
});
8086
}
8187
// [END get_firebase_user]
8288

8389
// [START get_algolia_user_token]
8490
// This complex HTTP function will be created as an ExpressJS app:
8591
// https://expressjs.com/en/4x/api.html
86-
const app = require("express")();
92+
const app = require('express')();
8793

8894
// We'll enable CORS support to allow the function to be invoked
8995
// from our app client-side.
90-
app.use(require("cors")({ origin: true }));
96+
app.use(require('cors')({ origin: true }));
9197

92-
// Then we'll also use a special "getFirebaseUser" middleware which
98+
// Then we'll also use a special 'getFirebaseUser' middleware which
9399
// verifies the Authorization header and adds a `user` field to the
94100
// incoming request:
95101
// https://gist.github.com/abehaskins/832d6f8665454d0cd99ef08c229afb42
96102
app.use(getFirebaseUser);
97103

98104
// Add a route handler to the app to generate the secured key
99-
app.get("/", (req, res) => {
105+
app.get('/', (req, res) => {
100106
// Create the params object as described in the Algolia documentation:
101107
// https://www.algolia.com/doc/guides/security/api-keys/#generating-api-keys
102108
const params = {
@@ -109,11 +115,11 @@ app.get("/", (req, res) => {
109115
// Call the Algolia API to generate a unique key based on our search key
110116
const key = client.generateSecuredApiKey(ALGOLIA_SEARCH_KEY, params);
111117

112-
// Then return this key as {key: "...key"}
118+
// Then return this key as {key: '...key'}
113119
res.json({ key });
114120
});
115121

116122
// Finally, pass our ExpressJS app to Cloud Functions as a function
117-
// called "getSearchKey";
123+
// called 'getSearchKey';
118124
exports.getSearchKey = functions.https.onRequest(app);
119125
// [END get_algolia_user_token]

0 commit comments

Comments
 (0)