Created
December 10, 2019 22:27
-
-
Save NdibeRaymond/51755b0c6aab5097e5e16f6cd16d1a02 to your computer and use it in GitHub Desktop.
This code illustrates how to use fuse.js in cloud functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Fuse = require("fuse.js"); | |
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. | |
const functions = require('firebase-functions'); | |
// The Firebase Admin SDK to access the Firebase Realtime Database. | |
const admin = require('firebase-admin'); | |
admin.initializeApp(); | |
SearchEngine = { | |
textSearch:(data,search_text,_keys=[],should_sort=false,_threshold=0.2,_location=0,_distance=100,max_pattern_length=32,min_match_charlength=1)=>{ | |
let newData = data; | |
if(search_text !== undefined && search_text!==""){ | |
let options = { | |
shouldSort: should_sort, | |
threshold: _threshold, | |
location: _location, | |
distance: _distance, | |
maxPatternLength: max_pattern_length, | |
minMatchCharLength: min_match_charlength, | |
keys:_keys}; | |
let fuse = new Fuse(newData, options); | |
newData = fuse.search(search_text); | |
} | |
return newData | |
} | |
} | |
exports.search_engine = functions.https.onRequest(async(req,res)=>{ | |
let events = await admin.database().ref(`events/`).once("value").then(snapshot=>snapshot.val()); | |
let eventsData = Object.values(events); | |
let text_search = req.query.text_search; | |
if(text_search !== "" && text_search !== "null" && text_search !== "undefined" && text_search !== null && text_search !== undefined){ | |
if(eventsData.length !== 0){ | |
eventsData = SearchEngine.textSearch(eventsData,text_search,["event_title","address","city","country"]); | |
} | |
} | |
res.set('Access-Control-Allow-Origin', '*').status(200).send(eventsData)// make sure to include ('Access-Control-Allow-Origin','*') //or you might face cors problem | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment