Figured out a method. Using the aggregate chapter data endpoint gives seemingly adequate reference as to a chapter's neighbors.
This is the only way actually.
Personally, it was a little bit tricky at first.
What i did first is to store the chapter ids of the aggregate endpoint in to an array.
but there are actually chapter with the same chapter number,
and there is actually this
none
chapter number and floating chapter number like chapter
1.5
for example.
The ideal way is to stored it into a three map where the key is the chapter number and value is a chapter id array.
That way, to find the next/previous chapter, you just need to get the next/previous node.
It can be pretty if you want to implement the
Change Group
feature easily.
Tip: Make "none" (or any string actually) chapter number to a way that it is always greater than any number.
But this sounded like an overkill solution, so i came back with just a simple array.
Since MangaDex already sort the response with volume and chapter ascendant.
We flatten the result into a simple array and find the chapter id index,
and increment or decrement this index to find the next/previous chapter.
Here is a code example in Typescript.
JavaScript:
// I am using Typescript here for clarity
type AdjacentChapter = {
volume?: string,
chapter?: string,
/// you can change it with an array id the logic still stay the same
id: string
}
const chapterId = "your chapter id";
const response = await fetch("https://api.mangadex.org/manga/[your chapter manga id here]/aggregate?groups[]=group1Id...").then(r => r.json());
const chapterAdjacentArray: AdjacentChapter[] = Object.entries(response.volumes).flatMap(([volume, chapters]) => {
return Object.entries(chapters).map(([chapter, entry]) => {
/// Included it here but you can remove it if you want.
const chapter_ids = [entry.id, ...entry.others];
return {
volume,
chapter,
/// kinda pointless, you can just use `entry.id` here
/// but if you want, you can change the `chapter_ids[0]` with a random value as an index
id: chapter_ids.includes(chapterId)? chapterId : chapter_ids[0]
}
});
});
/// We just need to find the id of the chapter in the array;
const chapterIndex = chapterAdjacentArray.findIndex(({id}) => id == chapterId);
/// TADA! we just need to increment or deincrement this index to find the next/previous chapter
/// I am using `at` here because it can be undefined
const nextChapterId = chapterAdjacentArray.at(chapterIndex + 1)?.id;
/// I made a quick bound check here
/// Javascript goes at the end of the array if the index is negative
const previousChapterId = chapterIndex - 1 < 0 ? undefinded : chapterAdjacentArray.at(chapterIndex - 1)?.id;