Skip to content

Instantly share code, notes, and snippets.

@jrodl3r
Last active November 1, 2019 20:21
Show Gist options
  • Save jrodl3r/a924bbc2bcf2ac6e2e9c4ed4f2a1629f to your computer and use it in GitHub Desktop.
Save jrodl3r/a924bbc2bcf2ac6e2e9c4ed4f2a1629f to your computer and use it in GitHub Desktop.
ElasticSearch - Cloud Functions
import * as functions from 'firebase-functions';
import * as firebase from 'firebase-admin';
firebase.initializeApp();
const env = functions.config();
const auth = {
username: env.elasticsearch.username,
password: env.elasticsearch.password,
};
const request = require('request-promise');
// Add Contact
export const addContact = functions.firestore
.document('contacts/{userID}')
.onCreate((snap, context) => {
const req = {
auth,
method: 'POST',
uri: env.elasticsearch.url + '/contacts/_doc/' + snap.id,
body: snap.data(),
json: true
};
return request(req);
});
// Update Contact
export const updateContact = functions.firestore
.document('contacts/{userID}')
.onUpdate(change => {
const req = {
auth,
method: 'POST',
uri: env.elasticsearch.url + '/contacts/_doc/' + change.after.id,
body: change.after.data(),
json: true
};
return request(req);
});
// Delete Contact
export const deleteContact = functions.firestore
.document('contacts/{userID}')
.onDelete(snap => {
const req = {
auth,
method: 'DELETE',
uri: env.elasticsearch.url + '/contacts/_doc/' + snap.id
};
return request(req);
});
// Search Contact
export const searchContact = functions.https.onCall((data, context) => {
const req = {
auth,
method: 'GET',
uri: env.elasticsearch.url + '/contacts/_search/',
body: {
query: {
simple_query_string: {
query: `${data.query}*`,
fields: ['company', 'name']
}
}
},
json: true
};
return request(req);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment