### Install KKBOX JavaScript SDK using npm Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/index.html This command installs the KKBOX JavaScript SDK package from npm, making it available for use in your project. Ensure you have Node.js and npm installed. ```bash $ npm install @kkbox/kkbox-js-sdk ``` -------------------------------- ### Install KKBOX SDK via NPM Source: https://github.com/kkbox/openapi-javascript/blob/master/README.md Command to install the official KKBOX JavaScript SDK package into your project dependencies. ```bash $ npm install @kkbox/kkbox-js-sdk ``` -------------------------------- ### Fetch Album Tracks using AlbumFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/AlbumFetcher.js~AlbumFetcher.html This example illustrates how to retrieve the tracks of an album using the AlbumFetcher. It accepts optional limit and offset parameters to control the number of tracks returned and the starting point of the results. The method returns a Promise with the track list. ```javascript api.albumFetcher.setAlbumID('someAlbumId').fetchTracks(limit, offset); ``` -------------------------------- ### Fetch All Mood Stations using MoodStationFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/MoodStationFetcher.js~MoodStationFetcher.html This example demonstrates how to use the MoodStationFetcher to retrieve all available mood stations. It assumes an 'api' object has been initialized with the SDK. ```javascript api.moodStationFetcher.fetchAllMoodStations(); ``` -------------------------------- ### KKBOX JavaScript SDK Usage Example Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/index.html This JavaScript code demonstrates how to use the KKBOX SDK to authenticate, fetch an access token, and then use that token to make an API call to search for tracks. It shows the basic flow of initializing Auth and Api objects and performing a search. ```javascript import { Auth, Api } from '@kkbox/kkbox-js-sdk'; // Create an auth object with client id and secret const auth = new Auth(client_id, client_secret); // Fetch your access token auth.clientCredentialsFlow .fetchAccessToken() .then(response => { const access_token = response.data.access_token; // Create an API object with your access token const api = new Api(access_token); // Fetch content with various fetchers api.searchFetcher .setSearchCriteria('五月天 派對動物', 'track') .fetchSearchResult() .then(response => { // Content from the KKBOX Open API console.log(response.data); // Continue to the next page api.searchFetcher.fetchNextPage(response).then(response => { console.log(response.data); }); }); }); ``` -------------------------------- ### GET /hasNextPage Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Fetcher.js~Fetcher.html Checks if there is an additional page available for the current API resource. ```APIDOC ## GET /hasNextPage ### Description Determines if a subsequent page exists for the current API resource based on the fulfillment state. ### Method GET ### Parameters #### Query Parameters - **fulfillment** (Object) - Required - The fulfillment object containing current API state. - **nextUriPath** (String) - Required - The URI path to check for availability. ### Response #### Success Response (200) - **Boolean** (Boolean) - Returns true if a next page is available, false otherwise. ### Response Example { "hasNext": true } ``` -------------------------------- ### Import NewReleaseCategoryFetcher - JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/NewReleaseCategoryFetcher.js~NewReleaseCategoryFetcher.html This snippet shows how to import the NewReleaseCategoryFetcher class from the '@kkbox/kkbox-js-sdk' package. This is the primary way to start using the fetcher in your JavaScript application. ```javascript import NewReleaseCategoryFetcher from '@kkbox/kkbox-js-sdk/src/api/NewReleaseCategoryFetcher.js' ``` -------------------------------- ### GET /new-release-categories Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/NewReleaseCategoryFetcher.js~NewReleaseCategoryFetcher.html Fetches a list of all available new release categories with optional pagination support. ```APIDOC ## GET /new-release-categories ### Description Retrieves a list of new release categories. Supports pagination via limit and offset parameters. ### Method GET ### Endpoint /new-release-categories ### Parameters #### Query Parameters - **limit** (number) - Optional - The size of one page. - **offset** (number) - Optional - The offset index for the first element. ### Request Example api.newReleaseCategoryFetcher.fetchAllNewReleaseCategories(); ### Response #### Success Response (200) - **data** (Array) - List of new release category objects. #### Response Example { "data": [ { "id": "Cng5IUIQhxb8w1cbsz", "title": "Pop" } ] } ``` -------------------------------- ### Fetch Charts and Check for Next Page using ChartFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/apitest.js.html Shows how to fetch charts and then check if there is a next page of results. This example also demonstrates attempting to fetch the next page, which is expected to fail in this scenario. ```javascript const chartFetcher = new ChartFetcher(httpClient); describe('#fetchCharts()', () => { it('should succeed and fetch next page should fail', done => { chartFetcher.fetchCharts().then(response => { response.status.should.be.exactly(200); chartFetcher.hasNextPage(response).should.be.false(); chartFetcher.fetchNextPage(response).then( response => { response.should.not.exists(); done(response); }, reject => { done(); } ); }); }); }); ``` -------------------------------- ### Fetch All Genre Stations and Next Page using GenreStationFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/apitest.js.html Illustrates fetching all genre stations and then subsequently fetching the next page of results. The example uses a callback to signal completion or failure. ```javascript const genreStationFetcher = new GenreStationFetcher(httpClient); describe('#fetchAllGenreStations()', () => { it('should succeed and fetch next page should succeed', done => { genreStationFetcher .fetchAllGenreStations(1) .then(response => { response.status.should.be.exactly(200); genreStationFetcher.fetchNextPage(response).then( response => { response.status.should.be.exactly(200); done(); }, reject => { done(reject); } ); }); }); }); ``` -------------------------------- ### GET /fetchNextPage Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Fetcher.js~Fetcher.html Fetches the next page of results for paged API endpoints. ```APIDOC ## GET /fetchNextPage ### Description Retrieves the next page of data for a given API resource using the provided URI path. ### Method GET ### Parameters #### Query Parameters - **fulfillment** (Object) - Required - The fulfillment object containing current API state. - **nextUriPath** (String) - Required - The URI path for the next page of results. ### Response #### Success Response (200) - **Promise** (Promise) - A promise that resolves with the next page of data. ### Response Example { "data": [...], "paging": { "next": "..." } } ``` -------------------------------- ### GET /search Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/SearchFetcher.js.html Performs a search query against the KKBOX database. Supports filtering by specific metadata and pagination. ```APIDOC ## GET /search ### Description Fetch search results based on a query string and optional type constraints. Results can be further filtered using the filter method. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **q** (string) - Required - The keyword to be searched. - **type** (string) - Optional - The type of search: 'artist', 'album', 'track', or 'playlist'. Multiple types can be separated by commas. - **territory** (string) - Required - The territory code (e.g., 'TW'). - **limit** (number) - Optional - The size of one page. - **offset** (number) - Optional - The offset index for the first element. ### Request Example { "q": "五月天 好好", "type": "track", "territory": "TW" } ### Response #### Success Response (200) - **data** (Object) - The search results containing tracks, albums, artists, or playlists. #### Response Example { "data": { "tracks": { "data": [...] }, "albums": { "data": [...] } } } ``` -------------------------------- ### Configure Electron Browser Window Source: https://github.com/kkbox/openapi-javascript/blob/master/README.md Example of disabling web security in an Electron BrowserWindow to allow cross-origin requests to the KKBOX Auth server. ```javascript mainWindow = new BrowserWindow({ width: 500, height: 500, useContentSize: true, webPreferences: { webSecurity: false } }); ``` -------------------------------- ### Import Fetcher Class from KKBOX SDK Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Fetcher.js~Fetcher.html This snippet shows how to import the Fetcher class from the '@kkbox/kkbox-js-sdk' package. It's a common starting point for using any of the API fetcher functionalities. ```javascript import Fetcher from '@kkbox/kkbox-js-sdk/src/api/Fetcher.js' ``` -------------------------------- ### Initialize and Fetch Shared Playlist Metadata Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/SharedPlaylistFetcher.js.html This snippet demonstrates how to initialize the SharedPlaylistFetcher with a playlist ID and then fetch its metadata. It utilizes the `setPlaylistID` method followed by `fetchMetadata`. The `fetchMetadata` method makes a GET request to the KKBOX API endpoint for shared playlists. ```javascript import { SHARED_PLAYLISTS as ENDPOINT } from '../Endpoint'; import Fetcher from './Fetcher'; export default class SharedPlaylistFetcher extends Fetcher { constructor(http, territory = 'TW') { super(http, territory); this.playlistID = undefined; } setPlaylistID(playlistID) { this.playlistID = playlistID; return this; } fetchMetadata() { return this.http.get(ENDPOINT + '/' + this.playlistID, { territory: this.territory }); } getWidgetUri() { return `https://widget.kkbox.com/v1/?id=${this.playlistID}&type=playlist`; } fetchTracks(limit = undefined, offset = undefined) { return this.http.get(ENDPOINT + '/' + this.playlistID + '/tracks', { territory: this.territory, limit: limit, offset: offset }); } } // Example Usage: // Assuming 'api' is an instance of your main KKBOX API client // api.sharedPlaylistFetcher.setPlaylistID('4nUZM-TY2aVxZ2xaA-').fetchMetadata(); ``` -------------------------------- ### Fetch All Mood Stations (JavaScript) Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/MoodStationFetcher.js.html Fetches all available mood stations for a specified territory. This method utilizes the internal HTTP client to make a GET request to the mood stations endpoint. It requires an initialized HTTP client instance and optionally accepts a territory code. ```javascript import { MOOD_STATIONS as ENDPOINT } from '../Endpoint'; import Fetcher from './Fetcher'; /** * Get mood stations. * @see https://docs-en.kkbox.codes/v1.1/reference#mood-stations */ export default class MoodStationFetcher extends Fetcher { /** * @ignore */ constructor(http, territory = 'TW') { super(http, territory); /** * @ignore */ this.moodStationID = undefined; } /** * Fetch all mood stations. * * @return {Promise} * @example api.moodStationFetcher.fetchAllMoodStations(); * @see https://docs-en.kkbox.codes/v1.1/reference#moodstations */ fetchAllMoodStations() { return this.http.get(ENDPOINT, { territory: this.territory }); } /** * Init the mood station fetcher. * * @param {string} moodStationID - The ID of a mood station. * @param {string} [territory = 'TW'] - ['TW', 'HK', 'SG', 'MY', 'JP'] The territory of a mood station. * @return {MoodStation} * @see https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id */ setMoodStationID(moodStationID, territory = 'TW') { this.moodStationID = moodStationID; this.territory = territory; return this; } /** * Fetch the mood station's metadata. * * @return {Promise} * @example api.moodStationFetcher.setMoodStationID('StGZp2ToWq92diPHS7').fetchMetadata(); * @see https://docs-en.kkbox.codes/v1.1/reference#moodstations-station_id */ fetchMetadata() { return this.http.get(ENDPOINT + '/' + this.moodStationID, { territory: this.territory }); } } ``` -------------------------------- ### Initialize Api with Token and Territory (JavaScript) Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Api.js~Api.html Demonstrates how to instantiate the Api class, requiring an access token and optionally a territory. The territory defaults to 'TW' if not provided. This is the primary way to set up API access. ```javascript const api = new Api(token); const apiWithTerritory = new Api(token, 'TW'); ``` -------------------------------- ### Initialize KKBOX API with Token and Territory (JavaScript) Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Api.js~Api.html Demonstrates how to initialize the KKBOX API client using a provided access token and territory code. This is a prerequisite for making any API requests. The constructor requires a string for the token and a string for the territory. ```javascript import Api from '@kkbox/kkbox-js-sdk/src/api/Api.js'; const token = 'YOUR_ACCESS_TOKEN'; const territory = 'TW'; // Example: Taiwan const kkboxApi = new Api(token, territory); ``` -------------------------------- ### Perform HTTP GET Request Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/HttpClient.js~HttpClient.html Executes an HTTP GET request to a specified endpoint with optional query parameters. This method is used to retrieve data from the KKBOX OpenAPI server. It returns a Promise that resolves with the response data. ```javascript async function fetchData(endpoint, params) { try { const response = await httpClient.get(endpoint, params); return response; } catch (error) { console.error('Error fetching data:', error); throw error; } } // Example usage: // fetchData('/v1.1/albums/abc', { country: 'tw' }).then(data => console.log(data)); ``` -------------------------------- ### Initialize Auth Module Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/auth/Auth.js~Auth.html Demonstrates how to import and instantiate the Auth class using a client ID and client secret. This is the entry point for managing authentication flows within the KKBOX SDK. ```javascript import Auth from '@kkbox/kkbox-js-sdk/src/auth/Auth.js'; const clientID = "YOUR_CLIENT_ID"; const clientSecret = "YOUR_CLIENT_SECRET"; const auth = new Auth(clientID, clientSecret); ``` -------------------------------- ### GET /featured-playlists Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/FeaturedPlaylistFetcher.js~FeaturedPlaylistFetcher.html Fetches a list of all featured playlists available on the platform. ```APIDOC ## GET /featured-playlists ### Description Fetch all featured playlists. The result is returned as a paged list. ### Method GET ### Endpoint /featured-playlists ### Parameters #### Query Parameters - **limit** (number) - Optional - The number of playlists to return in a single page. - **offset** (number) - Optional - The offset index for the first element to retrieve. ### Request Example ```javascript api.featuredPlaylistFetcher.fetchAllFeaturedPlaylists({ limit: 20, offset: 0 }); ``` ### Response #### Success Response (200) - **data** (object) - The collection of featured playlists. - **paging** (object) - Pagination metadata including next and previous links. #### Response Example { "data": [ { "id": "playlist_1", "title": "Featured Hits" } ], "paging": { "offset": 0, "limit": 20, "total": 100 } } ``` -------------------------------- ### GET /v1.1/genre-stations Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/GenreStationFetcher.js~GenreStationFetcher.html Fetches a list of all available genre stations with optional pagination support. ```APIDOC ## GET /v1.1/genre-stations ### Description Fetch a list of all genre stations. Supports pagination via limit and offset parameters. ### Method GET ### Endpoint /v1.1/genre-stations ### Parameters #### Query Parameters - **limit** (number) - Optional - The size for one page. - **offset** (number) - Optional - The offset index for first element. ### Request Example GET /v1.1/genre-stations?limit=10&offset=0 ### Response #### Success Response (200) - **data** (array) - List of genre station objects. #### Response Example { "data": [ { "id": "TYq3EHFTl-1EOvJM5Y", "title": "Pop" } ] } ``` -------------------------------- ### GET /shared-playlists/{playlist_id}/tracks Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/SharedPlaylistFetcher.js~SharedPlaylistFetcher.html Retrieves the track list for a shared playlist with support for pagination. ```APIDOC ## GET /shared-playlists/{playlist_id}/tracks ### Description Fetch track list of a shared playlist. ### Method GET ### Endpoint /shared-playlists/{playlist_id}/tracks ### Parameters #### Query Parameters - **limit** (number) - Optional - The size for one page. - **offset** (number) - Optional - The offset index for the first element. ### Request Example ```javascript api.sharedPlaylistFetcher.setPlaylistID('4nUZM-TY2aVxZ2xaA-').fetchTracks(); ``` ### Response #### Success Response (200) - **tracks** (array) - List of track objects. #### Response Example { "data": [{"id": "track1", "name": "Song Title"}], "paging": {"limit": 20, "offset": 0} } ``` -------------------------------- ### Importing and Using ChartFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/ChartFetcher.js~ChartFetcher.html Demonstrates how to import the ChartFetcher class and execute a request to fetch available chart playlists using the SDK instance. ```javascript import ChartFetcher from '@kkbox/kkbox-js-sdk/src/api/ChartFetcher.js'; // Assuming 'api' is an initialized instance of the KKBOX SDK api.chartFetcher.fetchCharts(); ``` -------------------------------- ### GET /shared-playlists/{playlist_id} Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/SharedPlaylistFetcher.js~SharedPlaylistFetcher.html Fetches the metadata for a specific shared playlist identified by the playlist ID. ```APIDOC ## GET /shared-playlists/{playlist_id} ### Description Fetches metadata of the shared playlist with the shared playlist fetcher. ### Method GET ### Endpoint /shared-playlists/{playlist_id} ### Parameters #### Path Parameters - **playlist_id** (string) - Required - The unique identifier of the playlist. ### Request Example ```javascript api.sharedPlaylistFetcher.setPlaylistID('4nUZM-TY2aVxZ2xaA-').fetchMetadata(); ``` ### Response #### Success Response (200) - **metadata** (object) - The playlist metadata object. #### Response Example { "id": "4nUZM-TY2aVxZ2xaA-", "title": "Playlist Name", "owner": "User" } ``` -------------------------------- ### Run SDK Tests Source: https://github.com/kkbox/openapi-javascript/blob/master/README.md Command to execute the test suite for the KKBOX SDK. ```bash $ npm test ``` -------------------------------- ### GET /v1.1/genre-stations/{station_id} Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/GenreStationFetcher.js~GenreStationFetcher.html Retrieves the metadata for a specific genre station identified by its unique ID. ```APIDOC ## GET /v1.1/genre-stations/{station_id} ### Description Fetch metadata of a specific genre station using its unique station ID. ### Method GET ### Endpoint /v1.1/genre-stations/{station_id} ### Parameters #### Path Parameters - **station_id** (string) - Required - The ID of the genre station. ### Request Example api.genreStationFetcher.setGenreStationID('TYq3EHFTl-1EOvJM5Y').fetchMetadata(); ### Response #### Success Response (200) - **id** (string) - The station ID. - **title** (string) - The station name. #### Response Example { "id": "TYq3EHFTl-1EOvJM5Y", "title": "Pop", "description": "The latest pop hits." } ``` -------------------------------- ### Search for content using SearchFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/SearchFetcher.js.html Demonstrates how to initialize a search query, apply optional filters to the results, and execute the fetch request using the KKBOX SDK. ```javascript api.searchFetcher .setSearchCriteria('五月天 好好') .filter({artist: '五月天'}) .fetchSearchResult(); ``` -------------------------------- ### Authenticate and Fetch Data with KKBOX SDK Source: https://github.com/kkbox/openapi-javascript/blob/master/README.md Demonstrates initializing the Auth object, performing a client credentials flow to obtain an access token, and using the Api object to search for tracks. ```javascript import { Auth, Api } from '@kkbox/kkbox-js-sdk'; const auth = new Auth(client_id, client_secret); auth.clientCredentialsFlow .fetchAccessToken() .then(response => { const access_token = response.data.access_token; const api = new Api(access_token); api.searchFetcher .setSearchCriteria('五月天 派對動物', 'track') .fetchSearchResult() .then(response => { console.log(response.data); api.searchFetcher.fetchNextPage(response).then(response => { console.log(response.data); }); }); }); ``` -------------------------------- ### Initialize KKBOX API Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/Api.js.html Initializes the main API client required to access all music resource fetchers. ```APIDOC ## POST /api/initialize ### Description Initializes the KKBOX API client with an access token and territory. This client acts as the entry point for all resource fetchers. ### Method POST ### Parameters #### Request Body - **token** (string) - Required - The access token obtained via the Auth flow. - **territory** (string) - Optional - The territory code (e.g., 'TW', 'HK', 'SG', 'MY', 'JP'). Defaults to 'TW'. ### Request Example { "token": "your_access_token", "territory": "TW" } ### Response #### Success Response (200) - **api** (object) - Returns an instance of the Api class containing initialized fetchers. #### Response Example { "status": "success", "message": "API client initialized" } ``` -------------------------------- ### GET /new-release-categories/{category_id} Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/NewReleaseCategoryFetcher.js~NewReleaseCategoryFetcher.html Fetches metadata for a specific new release category identified by its unique ID. ```APIDOC ## GET /new-release-categories/{category_id} ### Description Fetches metadata of the specific new release category initialized by the category ID. ### Method GET ### Endpoint /new-release-categories/{category_id} ### Parameters #### Path Parameters - **categoryID** (string) - Required - The unique identifier for the category. ### Request Example api.newReleaseCategoryFetcher.setCategoryID('Cng5IUIQhxb8w1cbsz').fetchMetadata(); ### Response #### Success Response (200) - **id** (string) - The category ID. - **title** (string) - The category name. #### Response Example { "id": "Cng5IUIQhxb8w1cbsz", "title": "Pop" } ``` -------------------------------- ### Importing and Using TrackFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/TrackFetcher.js~TrackFetcher.html Demonstrates how to import the TrackFetcher class and use it to retrieve metadata for a specific track ID. ```javascript import TrackFetcher from '@kkbox/kkbox-js-sdk/src/api/TrackFetcher.js'; // Initialize and fetch track metadata api.trackFetcher.setTrackID('KpnEGVHEsGgkoB0MBk').fetchMetadata(); ``` -------------------------------- ### GET /featured-playlist-categories Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/FeaturedPlaylistCategoryFetcher.js~FeaturedPlaylistCategoryFetcher.html Fetches a list of all available featured playlist categories. ```APIDOC ## GET /featured-playlist-categories ### Description Fetch all featured playlist categories available on the platform. ### Method GET ### Endpoint /featured-playlist-categories ### Response #### Success Response (200) - **data** (array) - List of category objects ### Request Example ```javascript api.featuredPlaylistCategoryFetcher.fetchAllFeaturedPlaylistCategories(); ``` ``` -------------------------------- ### Fetcher Class Constructor Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Fetcher.js~Fetcher.html Initializes a new Fetcher instance. It requires an Http client instance and an optional territory string. The territory defaults to 'TW' and can be one of ['TW', 'HK', 'SG', 'MY', 'JP']. ```javascript public constructor(http: Http, territory: string = 'TW') /** * @param {Http} http - The Http client instance. * @param {string} [territory='TW'] - The territory for the fetcher. Defaults to 'TW'. */ ``` -------------------------------- ### Initialize and Use ClientCredentialsFlow in JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/auth/ClientCredentialsFlow.js~ClientCredentialsFlow.html Demonstrates how to import the ClientCredentialsFlow class and execute the fetchAccessToken method to retrieve an authentication token for the KKBOX API. ```javascript import ClientCredentialsFlow from '@kkbox/kkbox-js-sdk/src/auth/ClientCredentialsFlow.js'; // Usage example for fetching an access token auth.clientCredentialsFlow.fetchAccessToken(); ``` -------------------------------- ### Initialize and Set Search Criteria Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/SearchFetcher.js~SearchFetcher.html Demonstrates how to initialize the SearchFetcher and set the search criteria for a specific type (e.g., 'artist', 'album', 'track', 'playlist'). This method prepares the fetcher for subsequent search operations. ```javascript const searchFetcher = new SearchFetcher(); searchFetcher.setSearchCriteria('query', 'artist'); ``` -------------------------------- ### GET /featured-playlist-categories/{category_id} Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/FeaturedPlaylistCategoryFetcher.js~FeaturedPlaylistCategoryFetcher.html Retrieves metadata for a specific featured playlist category. ```APIDOC ## GET /featured-playlist-categories/{category_id} ### Description Fetch metadata of a specific category initialized by the fetcher. ### Method GET ### Endpoint /featured-playlist-categories/{category_id} ### Parameters #### Path Parameters - **category_id** (string) - Required - The unique identifier for the category ### Request Example ```javascript api.featuredPlaylistCategoryFetcher.setCategoryID('LXUR688EBKRRZydAWb').fetchMetadata(); ``` ``` -------------------------------- ### Fetcher Class Documentation Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/Fetcher.js.html Documentation for the Fetcher class, its constructor, and its methods. ```APIDOC ## Class: Fetcher ### Description Base api fetcher. ### Constructor - **http** (Http) - An instance of the Http client. - **territory** (string, optional) - The territory for the fetcher. Defaults to 'TW'. Allowed values: ['TW', 'HK', 'SG', 'MY', 'JP']. ### Methods #### setTerritory(territory) - **Description**: Sets the fetcher's territory. - **Parameters**: - **territory** (string, optional) - The territory to set. Defaults to 'TW'. Allowed values: ['TW', 'HK', 'SG', 'MY', 'JP']. - **Returns**: `Fetcher` - The Fetcher instance for chaining. #### getPropertyByPath(object, path) - **Description**: Gets an object's nested property by path. (Internal use) - **Parameters**: - **object** (object) - The object to retrieve the property from. - **path** (string) - The path to the nested property. - **Returns**: `any` - The value of the nested property, or undefined if not found. #### fetchNextPage(fulfillment, nextUriPath) - **Description**: Fetches the next page of various paged APIs. - **Parameters**: - **fulfillment** (any) - The fulfillment object obtained from a Promise's onFulfillment function. - **nextUriPath** (String, optional) - The path to the next URI within the fulfillment object. Defaults to 'data.paging.next'. - **Returns**: `Promise` - A Promise that resolves with the data from the next page, or rejects if the next URI cannot be found. - **Example**: ```javascript api.albumFetcher .setAlbumID('KmRKnW5qmUrTnGRuxF') .fetchTracks() .then(response => { api.albumFetcher.fetchNextPage(response)); }); ``` #### hasNextPage(fulfillment, nextUriPath) - **Description**: Checks if the next page is available for various paged APIs. - **Parameters**: - **fulfillment** (any) - The fulfillment object obtained from a Promise's onFulfillment function. - **nextUriPath** (String, optional) - The path to the next URI within the fulfillment object. Defaults to 'data.paging.next'. - **Returns**: `Boolean` - True if a next page is available, false otherwise. - **Example**: ```javascript api.albumFetcher .setAlbumID('KmRKnW5qmUrTnGRuxF') .fetchTracks() .then(response => { if (api.albumFetcher.hasNextPage(response)) { // more data available } }); ``` ``` -------------------------------- ### HttpClient Class Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/HttpClient.js~HttpClient.html The HttpClient class is used to make authenticated HTTP requests to the KKBOX OpenAPI server. It supports GET and POST methods. ```APIDOC ## HttpClient Do request to open api server with authorization header and error catch. ### Constructor #### `new HttpClient(token: string)` Initializes the HttpClient with an access token. **Parameters:** * **token** (string) - Required - The access token needed for API authentication. ### Methods #### `get(endpoint: string, params: object): Promise` Performs an HTTP GET request to the specified endpoint. **Parameters:** * **endpoint** (string) - Required - The API endpoint to request. * **params** (object) - Optional - Query parameters for the request. **Returns:** A Promise that resolves with the API response. #### `post(endpoint: string, data: object): Promise` Performs an HTTP POST request to the specified endpoint. **Parameters:** * **endpoint** (string) - Required - The API endpoint to request. * **data** (object) - Required - The data to send in the request body. **Returns:** A Promise that resolves with the API response. ``` -------------------------------- ### GET /featured-playlist-categories/{category_id}/playlists Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/FeaturedPlaylistCategoryFetcher.js~FeaturedPlaylistCategoryFetcher.html Retrieves a list of playlists belonging to a specific featured playlist category. ```APIDOC ## GET /featured-playlist-categories/{category_id}/playlists ### Description Fetches a collection of playlists associated with a specific category ID. ### Method GET ### Endpoint /featured-playlist-categories/{category_id}/playlists ### Parameters #### Path Parameters - **category_id** (string) - Required - The unique identifier for the playlist category. #### Query Parameters - **limit** (number) - Optional - The size of one page. - **offset** (number) - Optional - The offset index for the first element. ### Request Example api.featuredPlaylistCategoryFetcher.setCategoryID('LXUR688EBKRRZydAWb').fetchPlaylists(); ### Response #### Success Response (200) - **data** (Array) - A list of playlist objects. #### Response Example { "data": [ { "id": "playlist_1", "title": "Featured Playlist" } ] } ``` -------------------------------- ### GET /featured-playlist-categories/{category_id}/playlists Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/FeaturedPlaylistCategoryFetcher.js~FeaturedPlaylistCategoryFetcher.html Fetches featured playlists associated with a specific category with pagination support. ```APIDOC ## GET /featured-playlist-categories/{category_id}/playlists ### Description Fetch featured playlists of the category initialized by the fetcher. Results are returned in a paged format. ### Method GET ### Endpoint /featured-playlist-categories/{category_id}/playlists ### Parameters #### Query Parameters - **limit** (number) - Optional - Number of items to return - **offset** (number) - Optional - Number of items to skip ### Request Example ```javascript api.featuredPlaylistCategoryFetcher.fetchPlaylists(20, 0); ``` ``` -------------------------------- ### Initialize KKBOX API with Access Token and Territory (JavaScript) Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/Api.js.html Initializes the KKBOX API client with an access token and an optional territory. The territory specifies the region for fetching data. This constructor sets up the internal HttpClient and initializes various fetcher instances. ```javascript import HttpClient from './HttpClient'; import SearchFetcher from './SearchFetcher'; import TrackFetcher from './TrackFetcher'; import AlbumFetcher from './AlbumFetcher'; import ArtistFetcher from './ArtistFetcher'; import FeaturedPlaylistFetcher from './FeaturedPlaylistFetcher'; import FeaturedPlaylistCategoryFetcher from './FeaturedPlaylistCategoryFetcher'; import NewReleaseCategoryFetcher from './NewReleaseCategoryFetcher'; import NewHitsPlaylistFetcher from './NewHitsPlaylistFetcher'; import GenreStationFetcher from './GenreStationFetcher'; import MoodStationFetcher from './MoodStationFetcher'; import ChartFetcher from './ChartFetcher'; import SharedPlaylistFetcher from './SharedPlaylistFetcher'; /** * Fetch KKBOX resources. */ export default class Api { /** * Need access token to initialize. * * @param {string} token - Get via Auth. * @param {string} [territory = 'TW'] - ['TW', 'HK', 'SG', 'MY', 'JP'] The territory for the fetcher. * @example new Api(token); * @example new Api(token, 'TW'); */ constructor(token, territory = 'TW') { this.territory = territory; this.httpClient = undefined; this.setToken(token); } /** * Set new token and create fetchers with the new token. * * @param {string} token - Get via Auth. * @example api.setToken(token); */ setToken(token) { this.httpClient = new HttpClient(token); /** * @type {SearchFetcher} */ this.searchFetcher = new SearchFetcher(this.httpClient, this.territory); /** * @type {TrackFetcher} */ this.trackFetcher = new TrackFetcher(this.httpClient, this.territory); /** * @type {AlbumFetcher} */ this.albumFetcher = new AlbumFetcher(this.httpClient, this.territory); /** * @type {ArtistFetcher} */ this.artistFetcher = new ArtistFetcher(this.httpClient, this.territory); /** * @type {FeaturedPlaylistFetcher} */ this.featuredPlaylistFetcher = new FeaturedPlaylistFetcher( this.httpClient, this.territory ); /** * @type {FeaturedPlaylistCategoryFetcher} */ this.featuredPlaylistCategoryFetcher = new FeaturedPlaylistCategoryFetcher( this.httpClient, this.territory ); /** * @type {NewReleaseCategoryFetcher} */ this.newReleaseCategoryFetcher = new NewReleaseCategoryFetcher( this.httpClient, this.territory ); /** * @type {NewHitsPlaylistFetcher} */ this.newHitsPlaylistFetcher = new NewHitsPlaylistFetcher( this.httpClient, this.territory ); /** * @type {GenreStationFetcher} */ this.genreStationFetcher = new GenreStationFetcher( this.httpClient, this.territory ); /** * @type {MoodStationFetcher} */ this.moodStationFetcher = new MoodStationFetcher( this.httpClient, this.territory ); } } ``` -------------------------------- ### Get Widget URI Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/SharedPlaylistFetcher.js~SharedPlaylistFetcher.html Generates the KKBOX web widget URI for the specified playlist. Returns a string representing the URL to embed the playlist widget. ```javascript const uri = api.sharedPlaylistFetcher.getWidgetUri(); ``` -------------------------------- ### Get Shared Playlist Widget URI - JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/SharedPlaylistFetcher.js~SharedPlaylistFetcher.html Retrieves the KKBOX web widget URI for a shared playlist. This URI can be used to embed the playlist in web pages. ```javascript const widgetUri = sharedPlaylistFetcher.getWidgetUri(); ``` -------------------------------- ### Fetch Access Token using TokenFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/auth/TokenFetcher.js~TokenFetcher.html Demonstrates how to use the fetchAccessToken method of the TokenFetcher class to obtain an access token. This method requires a params object as input and returns a Promise. ```javascript public fetchAccessToken(params: object): Promise ``` -------------------------------- ### Authenticate and Fetch Access Token using Auth Class Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/sdktest.js.html Demonstrates how to instantiate the Auth class with client credentials and fetch an access token using the clientCredentialsFlow. This is a prerequisite for making authenticated API calls. ```javascript import should from 'should'; import { Auth, Api } from '../'; import { kkbox_sdk } from '../../client_secrets.json'; const CLIENT_ID = kkbox_sdk.client_id; const CLIENT_SECRET = kkbox_sdk.client_secret; describe('SDK Begin to Test', () => { describe('Auth', () => { it('should get access token', () => { const auth = new Auth(CLIENT_ID, CLIENT_SECRET); return auth.clientCredentialsFlow.fetchAccessToken().then(response => { // ... further tests with the access token }); }); }); }); ``` -------------------------------- ### Get Shared Playlist Widget URI in JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/apitest.js.html Tests the generation of the widget URI for a shared playlist. It asserts that the generated URI matches the expected format, including the playlist ID. ```javascript sharedPlaylistFetcher.getWidgetUri().should.be.exactly( `https://widget.kkbox.com/v1/?id=${playlist_id}&type=playlist` ); done(); ``` -------------------------------- ### Fetch Access Token using Client Credentials Flow Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/apitest.js.html This snippet demonstrates how to fetch an access token using the Client Credentials Flow. It initializes a TokenFetcher with client ID and secret, then uses it to create a ClientCredentials instance and call fetchAccessToken. The response contains the access token, which is then used to initialize an HttpClient. ```javascript import should from 'should'; import HttpClient from '../api/HttpClient'; import TokenFetcher from '../auth/TokenFetcher'; import ClientCredentials from '../auth/ClientCredentialsFlow'; import { kkbox_sdk } from '../../client_secrets.json'; const CLIENT_ID = kkbox_sdk.client_id; const CLIENT_SECRET = kkbox_sdk.client_secret; describe('Api Begin to Test', () => { describe('ClientCredentials', () => { describe('#fetch the access token()', () => { it('should fetch access token', () => { const tokenFetcher = new TokenFetcher(CLIENT_ID, CLIENT_SECRET); const clientCredentials = new ClientCredentials(tokenFetcher); return clientCredentials.fetchAccessToken().then( response => { const access_token = response.data.access_token; access_token.should.be.ok; const httpClient = new HttpClient(access_token); // ... further tests using httpClient } ); }); }); }); }); ``` -------------------------------- ### Import GenreStationFetcher from kkbox-js-sdk Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/GenreStationFetcher.js~GenreStationFetcher.html This snippet shows how to import the GenreStationFetcher class from the @kkbox/kkbox-js-sdk library. This is the initial step to use the fetcher's functionalities. ```javascript import GenreStationFetcher from '@kkbox/kkbox-js-sdk/src/api/GenreStationFetcher.js' ``` -------------------------------- ### Import ArtistFetcher - JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/ArtistFetcher.js~ArtistFetcher.html Demonstrates how to import the ArtistFetcher class from the @kkbox/kkbox-js-sdk. This is the initial step to utilize the SDK's artist-related functionalities. ```javascript import ArtistFetcher from '@kkbox/kkbox-js-sdk/src/api/ArtistFetcher.js' ``` -------------------------------- ### Initialize API with Fake Token and Check Territory Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/test/sdktest.js.html Initializes the Api class with a fake token and a specified territory ('HK'). It then verifies that the territory property is correctly set. This is useful for testing API object instantiation without a valid token. ```javascript const api = new Api('FAKE_TOKEN', 'HK'); describe('Property checking', () => { it('should have HK as territory', done => { api.territory.should.be.exactly('HK'); done(); }); }); ``` -------------------------------- ### Fetch Album Metadata - JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/AlbumFetcher.js.html Fetches the metadata for a specific album using its ID. This method requires the album ID to be set beforehand using `setAlbumID`. It makes a GET request to the KKBOX API endpoint for albums. ```javascript import { ALBUMS as ENDPOINT } from '../Endpoint'; import Fetcher from './Fetcher'; /** * Fetch metadata and tracks of a album. * @see https://docs-en.kkbox.codes/v1.1/reference#albums */ export default class AlbumFetcher extends Fetcher { /** * @ignore */ constructor(http, territory = 'TW') { super(http, territory); /** * @ignore */ this.albumID = undefined; } /** * Set the album fetcher. * * @param {string} albumID - The ID of an album. * @return {AlbumFetcher} * @see https://docs-en.kkbox.codes/v1.1/reference#albums-album_id */ setAlbumID(albumID) { this.albumID = albumID; return this; } /** * Fetch metadata of the album you create. * * @return {Promise} * @example api.albumFetcher.setAlbumID('KmRKnW5qmUrTnGRuxF').fetchMetadata(); * @see https://docs-en.kkbox.codes/v1.1/reference#albums-album_id */ fetchMetadata() { return this.http.get(ENDPOINT + '/' + this.albumID, { territory: this.territory }); } /** * Get KKBOX web widget uri of the album. * @example https://widget.kkbox.com/v1/?id=4qtXcj31wYJTRZbb23&type=album * @return {string} */ getWidgetUri() { return `https://widget.kkbox.com/v1/?id=${this.albumID}&type=album`; } /** * Get tracks in an album. Result will be return with pagination. * * @param {number} [limit] - The size for one page. * @param {number} [offset] - The offset index for first element. * @return {Promise} * @example api.albumFetcher.setAlbumID('KmRKnW5qmUrTnGRuxF').fetchTracks(); * @see https://docs-en.kkbox.codes/v1.1/reference#albums-album_id-tracks */ fetchTracks(limit = undefined, offset = undefined) { return this.http.get(ENDPOINT + '/' + this.albumID + '/tracks', { territory: this.territory, limit: limit, offset: offset }); } } ``` -------------------------------- ### Fetcher Class Methods Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/Fetcher.js~Fetcher.html Provides methods to interact with paginated API data. `fetchNextPage` retrieves the next set of results, while `hasNextPage` checks if more data is available. `setTerritory` allows updating the fetcher's territory after initialization. ```javascript /** * Fetches the next page of results for paginated APIs. * @param {function} fulfillment - A callback function to handle the API response. * @param {string} nextUriPath - The URI path for the next page. * @returns {Promise} A promise that resolves with the next page of data. */ public fetchNextPage(fulfillment: fulfillment, nextUriPath: string): Promise /** * Checks if a next page of results is available for paginated APIs. * @param {function} fulfillment - A callback function to handle the API response. * @param {string} nextUriPath - The URI path for the next page. * @returns {boolean} True if a next page is available, false otherwise. */ public hasNextPage(fulfillment: fulfillment, nextUriPath: string): boolean /** * Sets or updates the territory for the fetcher. * @param {string} territory - The territory to set. * @returns {Fetcher} The current Fetcher instance for chaining. */ public setTerritory(territory: string): Fetcher ``` -------------------------------- ### Fetch All Genre Stations using GenreStationFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/GenreStationFetcher.js~GenreStationFetcher.html Demonstrates how to fetch all available genre stations using the fetchAllGenreStations method of the GenreStationFetcher. This method accepts optional limit and offset parameters for pagination and returns a Promise that resolves with the genre station data. ```javascript const genreStationFetcher = new GenreStationFetcher(); genreStationFetcher.fetchAllGenreStations(limit, offset) .then(data => { // Handle the fetched genre station data }) .catch(error => { // Handle errors }); ``` -------------------------------- ### Fetch All Featured Playlist Categories - JavaScript Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/file/src/api/FeaturedPlaylistCategoryFetcher.js.html Fetches all available featured playlist categories. This method utilizes the HTTP client to make a GET request to the relevant endpoint, including the territory information. It returns a Promise that resolves with the category data. ```javascript import { FEATURED_PLAYLISTS_CATEGORIES as ENDPOINT } from '../Endpoint'; import Fetcher from './Fetcher'; /** * List featured playlist categories. * @see https://docs-en.kkbox.codes/v1.1/reference#featured-playlist-categories */ export default class FeaturedPlaylistCategoryFetcher extends Fetcher { /** * @ignore */ constructor(http, territory = 'TW') { super(http, territory); /** * @ignore */ this.categoryID = undefined; } /** * Fetch all featured playlist categories. * * @return {Promise} * @example api.featuredPlaylistCategoryFetcher.fetchAllFeaturedPlaylistCategories(); * @see https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories */ fetchAllFeaturedPlaylistCategories() { return this.http.get(ENDPOINT, { territory: this.territory }); } /** * Init the featured playlist category fetcher. * * @param {string} categoryID - The category ID. * @return {FeaturedPlaylistCategoryFetcher} * @see https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id */ setCategoryID(categoryID) { this.categoryID = categoryID; return this; } /** * Fetch metadata of the category you init. * * @return {Promise} * @example api.featuredPlaylistCategoryFetcher.setCategoryID('LXUR688EBKRRZydAWb').fetchMetadata(); * @see https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id */ fetchMetadata() { return this.http.get(ENDPOINT + '/' + this.categoryID, { territory: this.territory }); } /** * Fetch featured playlists of the category with the category fetcher you init. Result will be paged. * * @param {number} [limit] - The size of one page. * @param {number} [offset] - The offset index for first element. * @return {Promise} * @example api.featuredPlaylistCategoryFetcher.setCategoryID('LXUR688EBKRRZydAWb').fetchPlaylists(); * @see https://docs-en.kkbox.codes/v1.1/reference#featuredplaylistcategories-category_id-playlists */ fetchPlaylists(limit = undefined, offset = undefined) { return this.http.get(ENDPOINT + '/' + this.categoryID + '/playlists', { territory: this.territory, limit: limit, offset: offset }); } } ``` -------------------------------- ### Get Album Widget URI using AlbumFetcher Source: https://github.com/kkbox/openapi-javascript/blob/master/docs/class/src/api/AlbumFetcher.js~AlbumFetcher.html Shows how to obtain the KKBOX web widget URI for an album. This URI can be used to embed album information on external websites. The method returns a Promise that resolves with the widget URI string. ```javascript api.albumFetcher.setAlbumID('someAlbumId').getWidgetUri(); ```