Use Express router for serpapi endpoint

This commit is contained in:
valadaptive 2023-12-04 12:56:22 -05:00
parent 414c9bd5fb
commit 35ce955b00
2 changed files with 28 additions and 33 deletions

View File

@ -3624,7 +3624,7 @@ require('./src/endpoints/classify').registerEndpoints(app, jsonParser);
require('./src/endpoints/caption').registerEndpoints(app, jsonParser);
// Web search extension
require('./src/endpoints/serpapi').registerEndpoints(app, jsonParser);
app.use('/api/serpapi', require('./src/endpoints/serpapi').router);
const tavernUrl = new URL(
(cliArguments.ssl ? 'https://' : 'http://') +

View File

@ -1,39 +1,34 @@
const fetch = require('node-fetch').default;
const express = require('express');
const { readSecret, SECRET_KEYS } = require('./secrets');
const { jsonParser } = require('../express-common');
/**
* 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(SECRET_KEYS.SERPAPI);
const router = express.Router();
if (!key) {
console.log('No SerpApi key found');
return response.sendStatus(401);
}
router.post('/search', jsonParser, async (request, response) => {
try {
const key = readSecret(SECRET_KEYS.SERPAPI);
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);
if (!key) {
console.log('No SerpApi key found');
return response.sendStatus(401);
}
});
}
module.exports = {
registerEndpoints,
};
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 = { router };