Last active
March 23, 2017 20:22
-
-
Save derBingle/b43e05615d0cda2b4a0d288af3db83ab to your computer and use it in GitHub Desktop.
Get list of books from Google Books API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const apiKey = << API KEY HERE >> | |
const google = require('googleapis'); | |
const serviceAccount = require('./key.json'); | |
const { client_email, private_key } = serviceAccount; | |
const scope = 'https://www.googleapis.com/auth/books' | |
const client = new google.auth.JWT(client_email, null, private_key, scope, null); | |
client.authorize(function (err, tokens) { | |
if (err) { | |
return console.log(err); | |
} | |
getGoogleTitles(client, 'Mark Twain') | |
.then(results => console.log(results)) | |
.catch(error => console.log(error)) | |
}); | |
// Authorize Google api and return results of apiRequest | |
function getTitles(author) { | |
return new Promise((resolve, reject) => { | |
client.authorize(function (err, tokens) { | |
if (err) { | |
return console.log(err); | |
} | |
let titles = apiRequest(client, author) | |
if (titles) resolve(titles); | |
else reject (err); | |
}) | |
}) | |
} | |
// Function returns a promise with the books by author | |
function apiRequest(client, author) { | |
return new Promise((resolve, reject) => { | |
// | |
const books = google.books({ version: 'v1', auth: client }); | |
const options = { | |
key: apiKey, | |
langRestrict: 'en', | |
maxResults: 5, | |
prettyPrint: false, | |
download: 'epub', | |
filter: 'free-ebooks', | |
country:'US', | |
fields: 'items(id,volumeInfo/title)', | |
q: `inauthor:"${author}"` | |
}; | |
// call the API method and pass options as the first argument | |
books.volumes.list(options, (err, titles) => { | |
if(err) reject(err); | |
else resolve(titles.items); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment