Can you identify the issue with the function below? How would you suggest fixing it?
list() {
return this.bookRepo.all().then(books =>
Promise.all(books.map(book =>
Promise.all([
this.bookRepo.contents(book.id),
this.bookRepo.chapters(book.id)
]).then(([contents, chapters]) =>
Promise.all(chapters.map(chapter =>
Promise.all([
this.bookRepo.contents(chapter.id),
this.bookRepo.sections(chapter.id)
]).then(([contents, sections]) =>
Promise.all(sections.map(section =>
this.bookRepo.contents(section.id).then(contents => [
section, contents
])))
.then(sections => [chapter, contents, sections]))))
.then(chapters => [book, contents, chapters])))));
}
The function above seems complex and difficult to maintain. How can we simplify it or make it more abstract?
This is the schema being used:
type BookId = string
type ChapterId = string
type SectionId = string
type ContentId = string
export type SourceId =
| ChapterId
| SectionId
| BookId
type Book = {
id: BookId,
name: string,
}
type Chapter = {
id: ChapterId,
bookId: BookId,
name: string
}
type Section = {
id: SectionId,
chapterId: ChapterId,
name: string
}
type Content = {
id: ContentId,
name: string,
sourceId: SourceId,
content: string
}