Skip to content

Commit

Permalink
move api calls to private api server
Browse files Browse the repository at this point in the history
  • Loading branch information
petertimwalker committed May 28, 2024
1 parent f2b2527 commit 7e70167
Show file tree
Hide file tree
Showing 4 changed files with 216 additions and 3 deletions.
50 changes: 50 additions & 0 deletions books.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const express = require('express');
const router = express.Router();
const axios = require('axios');

router.get('/', async (req, res) => {
const author = req.query.author;
const apiKey = process.env.API_KEY;
try {
const books = await fetchBooks(author, apiKey);
res.json(books);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
res.status(500).json({ error: 'An error occurred while fetching books' });
}
});

router.get('/book', async (req, res) => {
const bookId = req.query.bookId;
const apiKey = process.env.API_KEY;
console.log(
`https://www.googleapis.com/books/v1/volumes/${bookId}?key=${apiKey}`,
);
try {
const response = await axios.get(
`https://www.googleapis.com/books/v1/volumes/${bookId}?key=${apiKey}`,
);
res.json(response.data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
res
.status(500)
.json({ error: 'An error occurred while fetching book details' });
}
});

function fetchBooks(author, apiKey) {
let request = `https://www.googleapis.com/books/v1/volumes?q=inauthor:${author}&key=${apiKey}&orderBy=newest&maxResults=40`;

return axios
.get(request)
.then((response) => response.data.items)
.catch((error) =>
console.error(
'There has been a problem with your fetch operation:',
error,
),
);
}

module.exports = router;
159 changes: 158 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.7.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2"
"express": "^4.19.2",
"node-fetch": "^3.3.2"
}
}
6 changes: 5 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
const express = require('express');
const app = express();
const dotenv = require('dotenv');
const booksRouter = require('./books');
const cors = require('cors');
app.use(cors());
dotenv.config();

const isProduction = process.env.NODE_ENV === 'production';
Expand All @@ -25,10 +28,11 @@ app.get('/api/key', (req, res) => {
res.json({ apiKey: API_KEY });
});

app.use('/api/books', booksRouter);

if (isProduction) {
const https = require('https');
const fs = require('fs');
const cors = require('cors');

app.use(
cors({
Expand Down

0 comments on commit 7e70167

Please sign in to comment.