Skip to content

Instantly share code, notes, and snippets.

@Hyllesen
Created December 7, 2019 02:26
Show Gist options
  • Save Hyllesen/a32f2443a1529d5d282ff9d00a99b8bb to your computer and use it in GitHub Desktop.
Save Hyllesen/a32f2443a1529d5d282ff9d00a99b8bb to your computer and use it in GitHub Desktop.
//custom-search-apikey.js
/*
//Replace with your own api key and credentials
const googleCustomSearchApiKey = "BJzaSyCkY6EYcaQlbq57TqXosLEHdG3olY81WLA";
const cx = "0115429292988874712327:lo4lvgeu1bq";
module.exports = { googleCustomSearchApiKey, cx };
*/
const customSearchCredentials = require("./config/custom-search-apikey");
const request = require("request-promise");
async function searchOnCustomSearch({ apikey, cx, searchquery }) {
if (!apikey) {
apikey = customSearchCredentials.googleCustomSearchApiKey;
}
if (!cx) {
cx = customSearchCredentials.cx;
}
const url = `https://www.googleapis.com/customsearch/v1?key=${apikey}&cx=${cx}&q=${searchquery}&prettyPrint=false`;
try {
const result = await request.get(url, { json: true });
return result.items;
} catch (error) {
console.error(error.error);
throw new Error(
"Error fetching Google search results, is your google api credentials OK?"
);
}
}
module.exports = searchOnCustomSearch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment