/*
***********************************************************
SerpAPI Interface
Copyright (c) 2023 by Global Technologies Corporation
ALL RIGHTS RESERVED ...
***********************************************************
*/
// import the packs sdk
import * as coda from "@codahq/packs-sdk";
// create the pack
export const pack = coda.newPack();
pack.setUserAuthentication({
type: coda.AuthenticationType.QueryParamToken,
paramName: "api_key",
instructionsUrl: 'https://serpapi.com/dashboard',
});
// set the network domain
pack.addNetworkDomain('serpapi.com');
// define the static vars
var oResponse;
// ################################################################
//
// SERPAPI
//
// ################################################################
pack.addFormula({
resultType : coda.ValueType.String,
name: "serpAPI",
description: "Search the web.",
cacheTtlSecs: 0,
parameters: [
coda.makeParameter({
type: coda.ParameterType.String,
name: "q",
description: "Query string.",
}),
],
// execute the formula
execute: async function ([q], context) {
console.log("q: " + q);
if (q) {
let thisPromise = await serpAPI(q, context)
.then(json => {
oResponse = json;
});
console.log(JSON.stringify(oResponse));
let oOrganicResults = oResponse.body.organic_results;
var oResults = {};
for (let i in oOrganicResults) {
oResults[i] = {
"title" : oOrganicResults[i].title,
"link" : oOrganicResults[i].link,
"thumbnail" : oOrganicResults[i].thumbnail,
"date" : oOrganicResults[i].date,
"snippet" : oOrganicResults[i].snippet
}
}
// add the answer box
oResults["answerBox"] = oResponse.body["answer_box"]
} else {
oResponse = {};
}
console.log(JSON.stringify(oResults));
return(JSON.stringify(oResults));
}
});
//
// TEXT COMPLETION
//
async function serpAPI(q, context)
{
let url = "https://serpapi.com/search.json?engine=google&q=" + encodeURIComponent(q);
const response = await context.fetcher.fetch( {
url : url,
method : 'GET',
headers: {
'Content-Type' : 'application/json'
}
});
return(response);
}