refactor(ytmusic): rewrite Artist to TypeScript

This commit is contained in:
LuanRT
2022-07-22 05:21:02 -03:00
parent c12b1482fe
commit 9c7850d197
2 changed files with 54 additions and 35 deletions

View File

@@ -1,35 +0,0 @@
import Parser from '../index';
import { observe } from '../helpers';
class Artist {
#page;
#actions;
/**
* @param {object} response - API response.
* @param {import('../../core/Actions').default} actions
*/
constructor(response, actions) {
this.#page = Parser.parseResponse(response.data);
this.#actions = actions;
this.header = this.page.header;
const music_shelf = this.#page.contents_memo.get('MusicShelf');
const music_carousel_shelf = this.#page.contents_memo.get('MusicCarouselShelf');
/** @type {import('../classes/MusicShelf')[] | import('../classes/MusicCarouselShelf')[]} */
this.sections = observe([ ...music_shelf, ...music_carousel_shelf ]);
}
async getAllSongs() {
const shelf = this.sections.get({ type: 'MusicShelf' });
const page = await shelf.endpoint.call(this.#actions, 'YTMUSIC');
return page.contents_memo.get('MusicPlaylistShelf')?.[0] || [];
}
get page() {
return this.#page;
}
}
export default Artist;

View File

@@ -0,0 +1,54 @@
import Parser, { ParsedResponse } from '../index';
import Actions, { AxioslikeResponse } from '../../core/Actions';
import { InnertubeError } from '../../utils/Utils';
import MusicShelf from '../classes/MusicShelf';
import MusicCarouselShelf from '../classes/MusicCarouselShelf';
import MusicPlaylistShelf from '../classes/MusicPlaylistShelf';
import MusicImmersiveHeader from '../classes/MusicImmersiveHeader';
class Artist {
#page;
#actions;
header;
sections;
constructor(response: AxioslikeResponse | ParsedResponse, actions: Actions) {
this.#page = Parser.parseResponse((response as AxioslikeResponse).data);
this.#actions = actions;
this.header = this.page.header.item().as(MusicImmersiveHeader);
const music_shelf = this.#page.contents_memo.get('MusicShelf') as MusicShelf[];
const music_carousel_shelf = this.#page.contents_memo.get('MusicCarouselShelf') as MusicCarouselShelf[];
this.sections = [ ...music_shelf, ...music_carousel_shelf ];
}
async getAllSongs(): Promise<MusicPlaylistShelf | null> {
const music_shelves = this.sections.filter((section) => section.type === 'MusicShelf') as MusicShelf[];
if (!music_shelves.length)
throw new InnertubeError('Could not find any node of type MusicShelf.');
const shelf = music_shelves.find((shelf) => shelf.title === 'Songs') as MusicShelf;
if (!shelf)
throw new InnertubeError('Could not find target shelf (Songs).');
if (!shelf.endpoint)
throw new InnertubeError('Target shelf (Songs) did not have an endpoint.');
const page = await shelf.endpoint.call(this.#actions, 'YTMUSIC', true) as ParsedResponse;
const contents = page.contents_memo.get('MusicPlaylistShelf')?.[0]?.as(MusicPlaylistShelf) || null;
return contents;
}
get page(): ParsedResponse {
return this.#page;
}
}
export default Artist;