Advertisement
sheefoo

Untitled

Nov 13th, 2020
1,478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import * as functions from 'firebase-functions';
  2. import Fuse from 'fuse.js';
  3. import * as admin from 'firebase-admin';
  4.  
  5. admin.initializeApp();
  6.  
  7. export const search = functions.https.onRequest(async (req, res) => {
  8.     res = res.set('Access-Control-Allow-Origin', '*').status(200);
  9.  
  10.     const ingredients = await admin.database().ref('ff/').once('value').then(snapshot => snapshot.val());
  11.  
  12.     if (!ingredients) {
  13.         res.send([]);
  14.         return;
  15.     }
  16.     const fullData = Object.values(ingredients);
  17.  
  18.     const searchText = req.query.query as string;
  19.  
  20.     if (typeof searchText !== 'string'
  21.      || !searchText
  22.      || ['null', 'undefined'].includes(searchText)) {
  23.         res.status(400).send([ 'searchText' ]);
  24.         return;
  25.     }
  26.  
  27.     if (!fullData.length) {
  28.         res.send([]);
  29.         return;
  30.     }
  31.  
  32.     const fuse = new Fuse(fullData, {
  33.         keys: [ 'synonyms' ],
  34.         shouldSort: false,
  35.         threshold: 0.2,
  36.         location: 0,
  37.         distance: 100,
  38.         minMatchCharLength: 1,
  39.     });
  40.  
  41.     const resultIngredients = fuse.search(searchText);
  42.  
  43.     res.send(resultIngredients);
  44. });
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement