Home > Back-end >  How to avoid sharing Email on algolia, Using Firbase Functions
How to avoid sharing Email on algolia, Using Firbase Functions

Time:05-23

I am using Firebase functions to create Algolia indices for the full-text search app

here is how I create an index when someone post on Firebase:

export const onListingCreated = functions.firestore
  .document('Listings/{listingId}')
  .onCreate((snap, ctx) => {
    return index.saveObject({
      objectID: snap.id,
      ...snap.data(),
    })
  })

//...snap.data() has - AdTitle:"House" Email:"[email protected]"
//this works well the index is created like this on algolia

But I want to avoid sharing the email

I tried it Like this:

export const onListingCreated = functions.firestore
  .document('Listings/{listingId}')
  .onCreate((snap, ctx) => {
    return index.saveObject({
      objectID: snap.id,
      ...snap.data().AdTitle,
    })
  })

//on algolia the index was created like:
//0:H
//1:o
//2:u
//3:s
//4:e

I wanted to be AdTitle: "House"

Is there a way to avoid sharing sensitive information on algolia?

CodePudding user response:

In your case snap.data().AdTitle is the string House and you are spreading over the string which makes your output object look like that. Once you spread a string it is converted to an array. For example House is converted to ["H", "o", "u", "s", "e"] Now in javascript arrays are also type of object so when you try {...["H", "o", "u", "s", "e"]} it takes ["H", "o", "u", "s", "e"] as { 0: "H", 1: "o", 2: "u", 3: "s", 4: "e" } and spreads over that object giving what you have mentioned

let randomString = 'House'
let obj = {...randomString} //converts to array and then spreads the array
console.log(obj)

let arr = [...randomString]
console.log(arr)
let obj2 = {...arr}
console.log(obj2) //obj and obj2 give same result

Instead what you can do is

    let randomString = 'House'
    let obj = {AdTitle: randomString}
    console.log(obj)

Or you can delete the Email property from the data object and then use your usual implementation

  .onCreate((snap, ctx) => {
    const dataObj = snap.data()
    delete dataObj.Email
    return index.saveObject({
      objectID: snap.id,
      ...dataObj,
    })
  })
  • Related