Skip to content

Commit ba7fcd7

Browse files
committed
fix: Update NYT API call to v3, to fix broken v2 reqs
1 parent 0ca1050 commit ba7fcd7

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

controllers/api.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -264,18 +264,31 @@ exports.getQuickbooks = async (req, res) => {
264264
*/
265265
exports.getNewYorkTimes = async (req, res, next) => {
266266
const apiKey = process.env.NYT_KEY;
267+
const url = `https://api.nytimes.com/svc/books/v3/lists/current/young-adult-hardcover.json?api-key=${apiKey}`;
267268
try {
268-
const response = await fetch(`http://api.nytimes.com/svc/books/v2/lists?list-name=young-adult&api-key=${apiKey}`);
269+
const response = await fetch(url);
270+
const contentType = response.headers.get('content-type') || '';
269271
if (!response.ok) {
270-
const error = await response.json();
271-
throw new Error(`New York Times API - ${response.status} ${response.statusText} ${JSON.stringify(error.fault)}`);
272+
const bodyText = await response.text();
273+
console.error(`[NYT API] Error response:\nStatus: ${response.status} ${response.statusText}\nHeaders: ${JSON.stringify([...response.headers])}\nBody (first 500 chars):\n${bodyText.slice(0, 500)}`);
274+
throw new Error(`New York Times API - ${response.status} ${response.statusText}`);
275+
}
276+
if (!contentType.includes('application/json')) {
277+
const bodyText = await response.text();
278+
console.error(`[NYT API] Unexpected content-type: ${contentType}\nBody (first 500 chars):\n${bodyText.slice(0, 500)}`);
279+
throw new Error('NYT API did not return JSON. Check your API key and endpoint.');
272280
}
273281
const data = await response.json();
282+
if (!data.results || !data.results.books) {
283+
console.error('[NYT API] No "results.books" field in response:', data);
284+
throw new Error('NYT API response missing "results.books".');
285+
}
274286
res.render('api/nyt', {
275287
title: 'New York Times API',
276-
books: data.results,
288+
books: data.results.books,
277289
});
278290
} catch (error) {
291+
console.error('[NYT API] Exception:', error);
279292
next(error);
280293
}
281294
};

views/api/nyt.pug

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ block content
2727
each book in books
2828
tr
2929
td= book.rank
30-
td= book.book_details[0].title
31-
td.hidden-xs= book.book_details[0].description
32-
td= book.book_details[0].author
33-
td.hidden-xs= book.book_details[0].primary_isbn13
30+
td= book.title
31+
td.hidden-xs= book.description
32+
td= book.author
33+
td.hidden-xs= book.primary_isbn13

0 commit comments

Comments
 (0)