-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
79 lines (61 loc) · 1.98 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const axios = require('axios')
require('dotenv').config()
const fs = require('fs')
const CSVToJSON = require('csvtojson')
const JSONToCSV = require('json2csv').parse
const importFile = process.env.IMPORT
const exportFile = process.env.EXPORT
const search = async (term, author) => {
try {
console.log(author)
const response = await axios.get(`https://www.googleapis.com/books/v1/volumes?q=${term}+inauthor:${author}`)
return findISBN(response.data)
}
catch (error) {
console.error(`async error: at ${term} and ${author}: ${error}`)
}
}
const findISBN = (input) => {
// store output in these
let returnIsbnten = ''
let returnIsbnthirteen = ''
// grab first result
let targetObject = input.items[0]
// populate ISBNs
let twoIsbns = targetObject.volumeInfo.industryIdentifiers
twoIsbns.forEach(isbn => (
isbn.type === 'ISBN_13' ?
returnIsbnthirteen = isbn.identifier :
returnIsbnten = isbn.identifier
))
return [returnIsbnten, returnIsbnthirteen]
}
const createLibrary = async (inputFile, outputFile) => {
let isbnJSON = []
// Read data and convert to JSON
const operatingJSON = await CSVToJSON().fromFile(inputFile)
let length = operatingJSON.length
// Search for ISBNs and add ISBNs to JSON
for (let x = 0; x < length; x++) {
let term = operatingJSON[x].term
let author = operatingJSON[x].author
try {
let [isbn10, isbn13] = await search(term, author) // search returns an array of isbns
isbnJSON.push({
'isbn 10': isbn10,
'isbn 13': isbn13
})
} catch (err) {
console.error(err)
} finally {
continue
}
}
// Convert JSON to .csv
const output = JSONToCSV(isbnJSON, {
fields: ["isbn 10", "isbn 13"]
})
// Write to output file
fs.writeFileSync(outputFile, output)
}
createLibrary(importFile, exportFile)