Skip to content

Instantly share code, notes, and snippets.

@drewdaemon
Created August 15, 2019 03:52
Show Gist options
  • Save drewdaemon/cf051c4b3667c0333672e9fca9f293d5 to your computer and use it in GitHub Desktop.
Save drewdaemon/cf051c4b3667c0333672e9fca9f293d5 to your computer and use it in GitHub Desktop.
import { APIGatewayProxyHandler } from 'aws-lambda';
import 'source-map-support/register';
import axios from 'axios';
import * as cheerio from 'cheerio';
import LIBRARY_SEARCH_URL from './endpoint';
const SELECTORS = {
RESULT_ENTRIES: '.results_cell',
TITLE_LINK: '.displayDetailLink',
THUMBNAIL: '.thumbnail img',
AUTHOR_NAME: '.INITIAL_AUTHOR_SRCH'
}
function queryLibrary(queryStr) {
const url = new URL(LIBRARY_SEARCH_URL);
url.search = `qu=${queryStr.replace(' ', '+')}`;
return axios.get(url.href);
}
function extractEntries(html) {
const $ = cheerio.load(html);
const results = $(SELECTORS.RESULT_ENTRIES);
const entries = [];
results.each((_, elem) => {
const rawThumbnailSrc = $(SELECTORS.THUMBNAIL, elem).attr('src');
const thumbnailSrc = rawThumbnailSrc.match('no_image.png') ? '' : rawThumbnailSrc;
const authorText = $(SELECTORS.AUTHOR_NAME, elem).text();
const authorName = authorText.replace('by', '').trim();
const result = {
title: $(SELECTORS.TITLE_LINK, elem).text(),
thumbnail: thumbnailSrc,
author: authorName
};
entries.push(result);
});
return entries;
}
export const query: APIGatewayProxyHandler = async (event, _context) => {
if (!event.queryStringParameters || !event.queryStringParameters.q) {
return {
statusCode: 400,
body: JSON.stringify({
message: 'No query provided'
}),
};
}
const res = await queryLibrary(event.queryStringParameters.q);
const resHTML = res.data;
const entries = extractEntries(resHTML);
return {
statusCode: 200,
body: JSON.stringify({
entries
})
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment