Last active
October 8, 2024 17:42
-
-
Save ProfAvery/f87811d1ff74ae5792fb7a1d5581b1ab to your computer and use it in GitHub Desktop.
REST vs. GraphQL - Summer 2024 AMSE Bootcamp
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 query = ` | |
query { | |
artists(where: {name: "Red Hot Chili Peppers"}) { | |
albums { | |
title | |
} | |
} | |
} | |
`; | |
const response = await fetch('http://localhost:4000/graphql', { | |
method: 'POST', | |
body: JSON.stringify({ | |
query, | |
variables: null, | |
}), | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}); | |
const result = await response.json(); | |
for (const album of result.data.artists[0].albums) { | |
console.log(album.title); | |
} |
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
// Luckily, the API provides a way to filter the albums by artist. | |
let response = await fetch('http://localhost:8000/api/tables/artists/rows?_filters=name%3ARed%20Hot%20Chili%20Peppers'); | |
let result = await response.json(); | |
const artistId = result.data[0].ArtistId; | |
// Otherwise, we would have to iterate over all artists to find the one we want. | |
/* | |
let response, result; | |
let json = { "next": "/tables/artists/rows" }; | |
do { | |
response = await fetch(`http://localhost:8000/api${json.next}`); | |
json = await response.json(); | |
result = json.data.find(artist => artist.Name === 'Red Hot Chili Peppers'); | |
if (result) { | |
break; | |
} | |
} while (json.next); | |
const artistId = result.ArtistId; | |
*/ | |
// We could also iterate here, but we would need to check all albums because | |
// an artist can have mutliple albums. and the list of albums might span | |
// multiple pages. | |
response = await fetch(`http://localhost:8000/api/tables/albums/rows?_filters=ArtistId%3A${artistId}`); | |
result = await response.json(); | |
for (const album of result.data) { | |
console.log(album.Title); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment