To complete this task, I will create a TypeScript function called fetchAnime that retrieves 50 anime results from the MyAnimeList v2 API using the native fetch API. The function will have a type definition for its return value.
First, let's create a new TypeScript file called anime.ts:
// anime.ts
type Anime = {
node_id: number;
name: string;
site_url: string;
};
type FetchAnimeResponse = {
status: 'success';
data: Anime[];
} | {
status: 'error';
message: string;
};
async function fetchAnime(): Promise<FetchAnimeResponse> {
const url = 'https://graphql-poc.myanimelist.net/graphql';
const query = `
query ($limit: Int!, $offset: Int!) {
Page(limit: $limit, offset: $offset) {
pageInfo {
hasNextPage
}
media (id: 100, format: MANGA) {
id
name {
full
}
siteUrl
}
}
}
`;
const variables = {
limit: 50,
offset: 0,
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
const data = await response.json();
if (data.errors) {
return {
status: 'error',
message: data.errors[0].message,
};
}
const animeData = data.data.Page.media.map((anime) => ({
node_id: anime.id,
name: anime.name.full,
site_url: anime.siteUrl,
}));
return {
status: 'success',
data: animeData,