diff --git a/public/scripts/secrets.js b/public/scripts/secrets.js index edf4123dc..1e0133c6e 100644 --- a/public/scripts/secrets.js +++ b/public/scripts/secrets.js @@ -12,6 +12,7 @@ export const SECRET_KEYS = { AI21: 'api_key_ai21', SCALE_COOKIE: 'scale_cookie', PALM: 'api_key_palm', + SERPAPI: 'api_key_serpapi', } const INPUT_MAP = { diff --git a/server.js b/server.js index d86e8df05..c3f47880b 100644 --- a/server.js +++ b/server.js @@ -3528,6 +3528,9 @@ require('./src/classify').registerEndpoints(app, jsonParser); // Image captioning require('./src/caption').registerEndpoints(app, jsonParser); +// Web search extension +require('./src/serpapi').registerEndpoints(app, jsonParser); + const tavernUrl = new URL( (cliArguments.ssl ? 'https://' : 'http://') + (listen ? '0.0.0.0' : '127.0.0.1') + diff --git a/src/secrets.js b/src/secrets.js index f59da2779..6da764529 100644 --- a/src/secrets.js +++ b/src/secrets.js @@ -21,6 +21,7 @@ const SECRET_KEYS = { ONERING_URL: 'oneringtranslator_url', DEEPLX_URL: 'deeplx_url', PALM: 'api_key_palm', + SERPAPI: 'api_key_serpapi', } /** diff --git a/src/serpapi.js b/src/serpapi.js new file mode 100644 index 000000000..38fc6928a --- /dev/null +++ b/src/serpapi.js @@ -0,0 +1,39 @@ +const fetch = require('node-fetch').default; +const { readSecret } = require('./secrets'); + +/** + * Registers the SerpApi endpoints. + * @param {import("express").Express} app + * @param {any} jsonParser + */ +function registerEndpoints(app, jsonParser) { + app.post('/api/serpapi/search', jsonParser, async (request, response) => { + try { + const key = readSecret('serpapi_key'); + + if (!key) { + console.log('No SerpApi key found'); + return response.sendStatus(401); + } + + const { query } = request.body; + const result = await fetch(`https://serpapi.com/search.json?q=${encodeURIComponent(query)}&api_key=${key}`); + + if (!result.ok) { + const text = await result.text(); + console.log('SerpApi request failed', result.statusText, text); + return response.status(500).send(text); + } + + const data = await result.json(); + return response.json(data); + } catch (error) { + console.log(error); + return response.sendStatus(500); + } + }); +} + +module.exports = { + registerEndpoints, +};