### Getting Started with JikanClient Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/00-START-HERE.txt Quick guide to importing, initializing the JikanClient, calling an endpoint, and handling errors. ```APIDOC ## Getting Started ### Import and Initialize ```typescript import { JikanClient, JikanError } from 'myanimelist-wrapper'; const jikan = new JikanClient(); ``` ### Calling an Endpoint ```typescript try { const anime = await jikan.anime.getById(5114); console.log(anime.data.title); } catch (error) { // Handle errors } ``` ### Error Handling ```typescript try { // ... API call ... } catch (error) { if (error instanceof JikanError) { console.error('Jikan API Error:', error.message); // Handle specific Jikan errors } else { console.error('An unexpected error occurred:', error); } } ``` ### Rate Limiting ```typescript // Add a delay between requests to respect rate limits await new Promise(r => setTimeout(r, 400)); ``` Refer to `quick-reference.md` for all method signatures and `errors.md` for error details. ``` -------------------------------- ### Import and Initialize JikanClient Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Import the JikanClient and create a new instance to start making requests. This is the basic setup for using the wrapper. ```typescript import { JikanClient } from 'myanimelist-wrapper'; // Create a new client const jikan = new JikanClient(); // Use it! const anime = await jikan.anime.getById(5114); console.log(anime.data.title); ``` -------------------------------- ### Install Dependencies Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/CONTRIBUTING.md Install all necessary project dependencies using npm. This should be done after cloning the repository. ```bash npm install ``` -------------------------------- ### Get Season Anime Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of fetching season anime with specific query parameters. Ensure the Jikan instance is initialized. ```typescript await jikan.seasons.getSeason(2024, 'winter', { filter: 'tv', sfw: true, limit: 25 }); ``` -------------------------------- ### Get Schedules Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of fetching scheduled anime for a specific day. Supports filtering by day, SFW status, and pagination. ```typescript await jikan.schedules.getSchedules({ filter: 'monday', sfw: true, limit: 25 }); ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Clone the repository and install project dependencies using npm. ```bash git clone https://github.com/firrthecreator/myanimelist-wrapper.git cd myanimelist-wrapper npm install npm run build npm test npm run format npm run lint ``` -------------------------------- ### Get User Anime List Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of retrieving a user's anime list, filtered by status and limited to a specific number of results. ```typescript await jikan.users.getAnimeList('username', { status: 'watching', limit: 50 }); ``` -------------------------------- ### Search People Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of how to use the search functionality for people with specific query parameters. ```typescript await jikan.people.search({ q: 'sora yama', order_by: 'favorites', sort: 'desc' }); ``` -------------------------------- ### Install MyAnimeList Wrapper with npm Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Use npm to install the package. This is the standard way to add the wrapper to your Node.js project. ```bash npm install myanimelist-wrapper ``` -------------------------------- ### Get Top Anime Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of fetching top anime with filtering by status and pagination. Available filters include 'airing', 'upcoming', 'byPopularity', and 'favorite'. ```typescript await jikan.top.getAnime({ filter: 'airing', limit: 25, page: 1 }); ``` -------------------------------- ### Get Anime for a Specific Season Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Example of how to fetch anime for the winter and spring seasons, with an option to filter by TV series for spring. ```typescript const winter2024 = await jikan.seasons.getSeason(2024, 'winter'); const spring2024 = await jikan.seasons.getSeason(2024, 'spring', { filter: 'tv' }); ``` -------------------------------- ### Node.js/Express/NestJS Usage Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Example of how to use the JikanClient within a Node.js server environment, specifically for an Express route handler. ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient(); export async function getAnime(req, res) { try { const anime = await jikan.anime.getById(req.params.id); res.json(anime.data); } catch (error) { res.status(500).json({ error: error.message }); } } ``` -------------------------------- ### Get Anime Genres Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of fetching anime genres. The 'filter' parameter can be set to 'genres', 'explicit_genres', 'themes', or 'demographics'. ```typescript await jikan.genres.getAnimeGenres({ filter: 'genres' }); ``` -------------------------------- ### Search Manga Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of how to use the search functionality for manga with specific query parameters. ```typescript await jikan.manga.search({ q: 'berserk', type: 'manga', status: 'publishing', order_by: 'chapters', sort: 'desc' }); ``` -------------------------------- ### Search Characters Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of how to use the search functionality for characters with specific query parameters. ```typescript await jikan.characters.search({ q: 'luffy', order_by: 'favorites', sort: 'desc', limit: 10 }); ``` -------------------------------- ### Install MyAnimeList Wrapper with yarn Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Use yarn to install the package. This is an alternative package manager for Node.js projects. ```bash yarn add myanimelist-wrapper ``` -------------------------------- ### Web Backend Proxy Example (Node.js/Express) Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Example of a backend Node.js/Express server that acts as a proxy to fetch anime data using the JikanClient and serve it to the frontend. ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient(); app.get('/api/anime/:id', async (req, res) => { try { const anime = await jikan.anime.getById(parseInt(req.params.id)); res.json(anime.data); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` -------------------------------- ### Pagination Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Shows how to fetch data for the first page and the next page, and how to check for the existence of more pages. ```typescript // First page const page1 = await jikan.anime.search({ q: 'naruto', limit: 25, page: 1 }); // Next page const page2 = await jikan.anime.search({ q: 'naruto', limit: 25, page: 2 }); // Check if more pages available if (page1.pagination.has_next_page) { console.log('More results available'); } ``` -------------------------------- ### Search with Pagination Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Demonstrates how to search for anime with pagination to retrieve all results. ```APIDOC ## Search with Pagination This example shows how to fetch all anime matching a query, handling pagination. ```typescript async function searchAnime(query: string) { let page = 1; let hasMore = true; const allResults = []; while (hasMore) { const response = await jikan.anime.search({ q: query, page, limit: 25 }); allResults.push(...response.data); hasMore = response.pagination.has_next_page; page++; // Rate limiting await new Promise(r => setTimeout(r, 400)); } return allResults; } ``` ``` -------------------------------- ### Install MyAnimeList Wrapper with pnpm Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Use pnpm to install the package. This is another alternative package manager for Node.js projects. ```bash pnpm add myanimelist-wrapper ``` -------------------------------- ### Troubleshooting: TypeScript Installation Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Ensure TypeScript is installed as a development dependency and that your tsconfig.json is correctly configured. ```bash npm install --save-dev typescript ``` -------------------------------- ### Search Clubs Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Example of searching for clubs with specific criteria like category, type, and sorting by member count. ```typescript await jikan.clubs.search({ category: 'anime', type: 'public', order_by: 'members_count', sort: 'desc', limit: 10 }); ``` -------------------------------- ### Error Handling Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Provides an example of how to handle potential errors, including specific status codes like 404 and 429. ```APIDOC ## Error Handling This example shows how to use a try-catch block to handle potential errors from API requests, checking for specific error types and statuses. ```typescript try { const anime = await jikan.anime.getById(5114); console.log(anime.data.title); } catch (error) { if (error instanceof JikanError) { if (error.status === 404) { console.error('Not found'); } else if (error.status === 429) { console.error('Rate limited'); } else { console.error(`Error: ${error.message}`); } } } ``` ``` -------------------------------- ### Example Usage of Review Query Parameters Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Demonstrates how to use the ReviewQueryParams to fetch anime reviews with specific filters. ```typescript await jikan.reviews.getAnimeReviews({ preliminary: false, spoiler: false, limit: 25 }); ``` -------------------------------- ### Web Frontend API Call Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Example of how a web frontend (React, Vue, Angular) should call a backend API to fetch anime data, respecting CORS restrictions. ```typescript // Frontend code async function getAnime(id: number) { // Call your backend API, not the Jikan API directly const response = await fetch(`/api/anime/${id}`); return response.json(); } ``` -------------------------------- ### Batch Fetch with Rate Limiting Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Shows how to fetch data in batches with delays to avoid rate limiting. ```APIDOC ## Batch with Rate Limiting This example demonstrates fetching multiple anime by ID in batches, with a delay between each batch. ```typescript async function batchFetch(ids: number[]) { const results = []; const batchSize = 5; for (let i = 0; i < ids.length; i += batchSize) { const batch = ids.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(id => jikan.anime.getById(id)) ); results.push(...batchResults); // Delay between batches if (i + batchSize < ids.length) { await new Promise(r => setTimeout(r, 1000)); } } return results; } ``` ``` -------------------------------- ### Get Anime and Manga Recommendations Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Retrieve recommendations for anime and manga. ```typescript await jikan.recommendations.getAnimeRecommendations() await jikan.recommendations.getMangaRecommendations() ``` -------------------------------- ### Client Initialization Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Demonstrates how to initialize the JikanClient with default and custom configurations. ```APIDOC ## Client Configuration ### Default Configuration ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient(); ``` ### Custom Configuration ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikanCustom = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 30000, headers: { 'Accept': 'application/json', 'User-Agent': 'MyAnimeList-Wrapper/1.0' }, retryAttempts: 3, retryDelay: 1000, cacheEnabled: true, cacheTTL: 3600000 }); ``` ### Configuration Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `baseUrl` | string | `https://api.jikan.moe/v4` | The base URL for the Jikan API | | `timeout` | number | `30000` | Request timeout in milliseconds | | `headers` | object | `{}` | Custom HTTP headers | | `retryAttempts` | number | `3` | Number of retry attempts on failure | | `retryDelay` | number | `1000` | Delay between retries in milliseconds | | `cacheEnabled` | boolean | `true` | Enable response caching | | `cacheTTL` | number | `3600000` | Cache time-to-live in milliseconds | ``` -------------------------------- ### Full JikanClient Configuration Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Demonstrates comprehensive configuration options for JikanClient, including base URL, timeout, custom headers, retry settings, and caching. ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient({ // Base API URL baseUrl: 'https://api.jikan.moe/v4', // Request timeout (ms) timeout: 30000, // Custom HTTP headers headers: { 'Accept': 'application/json', 'Accept-Encoding': 'gzip', 'User-Agent': 'MyApp/1.0' }, // Retry configuration retryAttempts: 3, retryDelay: 1000, // Response caching cacheEnabled: true, cacheTTL: 3600000 // 1 hour }); ``` -------------------------------- ### Fetch Related Data Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Illustrates fetching multiple related data points for an anime concurrently using Promise.all. ```APIDOC ## Fetch Related Data This example fetches anime details, characters, episodes, and statistics simultaneously. ```typescript async function getFullAnimeInfo(id: number) { const [anime, characters, episodes, stats] = await Promise.all([ jikan.anime.getById(id), jikan.anime.getCharacters(id), jikan.anime.getEpisodes(id), jikan.anime.getStatistics(id) ]); return { anime: anime.data, characters: characters.data, episodes: episodes.data, stats: stats.data }; } ``` ``` -------------------------------- ### Anime Filtering Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Shows how to filter anime search results by type, status, and rating. ```typescript // Anime filters await jikan.anime.search({ type: 'tv', status: 'airing', rating: 'pg13' }); ``` -------------------------------- ### Jikan Client Initialization and Configuration Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/INDEX.md Documentation for initializing the JikanClient and configuring its options, including base URL, timeout, and custom headers. ```APIDOC ## JikanClient Configuration ### Constructor - **Signature**: `new JikanClient(options?: JikanClientOptions)` ### Options Interface: `JikanClientOptions` - **baseUrl**: `string` - The base URL for the Jikan API (defaults to official API). - **timeout**: `number` - Request timeout in milliseconds (defaults to 30000). - **headers**: `Record` - Custom HTTP headers to include in requests. ### Usage Examples ```typescript import { JikanClient } from 'myanimelist-wrapper'; // Default configuration const client = new JikanClient(); // Custom configuration const customClient = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 10000, headers: { 'X-Custom-Header': 'value' } }); ``` ``` -------------------------------- ### Client Configuration: Default and Custom Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Demonstrates initializing the JikanClient with default settings and with custom options for base URL, timeout, headers, retries, and caching. ```typescript import { JikanClient } from 'myanimelist-wrapper'; // Default configuration const jikan = new JikanClient(); // Custom configuration const jikanCustom = new JikanClient({ // Base URL of the Jikan API baseUrl: 'https://api.jikan.moe/v4', // Request timeout in milliseconds timeout: 30000, // Custom headers headers: { 'Accept': 'application/json', 'User-Agent': 'MyAnimeList-Wrapper/1.0' }, // Enable/disable automatic retries retryAttempts: 3, retryDelay: 1000, // Cache configuration cacheEnabled: true, cacheTTL: 3600000 // 1 hour }); ``` -------------------------------- ### Get Recommendations Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieve anime recommendations. The response data includes pairs of recommended anime. ```typescript const recommendations = await jikan.recommendations.getRecommendations(); recommendations.data.forEach(rec => { console.log( `If you like ${rec.entry_1.title}, try ${rec.entry_2.title}` ); }); ``` -------------------------------- ### Initialize JikanClient Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Create a JikanClient instance with default settings or custom configuration including base URL, timeout, and headers. ```typescript import { JikanClient } from 'myanimelist-wrapper'; // Create client with default settings const jikan = new JikanClient(); // Create client with custom configuration const jikanCustom = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 60000, // 60 seconds headers: { 'User-Agent': 'MyApp/1.0' } }); ``` -------------------------------- ### Check Method Signatures Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/TROUBLESHOOTING.md Verify that you are using the correct method names provided by the library to avoid runtime errors. For example, use 'getById' instead of 'get'. ```typescript // Make sure you're using the right method const anime = await jikan.anime.getById(5114); // ✅ Correct const anime = await jikan.anime.get(5114); // ❌ Wrong - method doesn't exist const characters = await jikan.anime.getCharacters(5114); // ✅ Correct const characters = await jikan.anime.characters(5114); // ❌ Wrong ``` -------------------------------- ### Complete Anime Information Fetch Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/anime-endpoint.md Demonstrates how to use the JikanClient to fetch various details about an anime, including its main data, characters, episodes, recommendations, and statistics. Includes error handling for JikanError. ```typescript import { JikanClient, JikanError } from 'myanimelist-wrapper'; const jikan = new JikanClient(); async function getAnimeInfo() { try { // Get main anime data const anime = await jikan.anime.getById(5114); console.log(`Title: ${anime.data.title}`); console.log(`Episodes: ${anime.data.episodes}`); // Get characters const characters = await jikan.anime.getCharacters(5114); console.log(`Main character: ${characters.data[0].character.name}`); // Get episodes const episodes = await jikan.anime.getEpisodes(5114); console.log(`Total episode pages: ${episodes.pagination.last_visible_page}`); // Get recommendations const recs = await jikan.anime.getRecommendations(5114); if (recs.data.length > 0) { console.log(`Recommended: ${recs.data[0].entry.title}`); } // Get statistics const stats = await jikan.anime.getStatistics(5114); console.log(`Completed by ${stats.data.completed} users`); } catch (error) { if (error instanceof JikanError) { console.error(`Error: ${error.status} - ${error.message}`); } } } getAnimeInfo(); ``` -------------------------------- ### Build the Project Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/CONTRIBUTING.md Compile the project's source code into distributable files. This is typically done before deployment or testing in a production-like environment. ```bash npm run build ``` -------------------------------- ### Initialize JikanClient and Fetch Anime by ID Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/00-START-HERE.txt Demonstrates basic client initialization and fetching a single anime entry by its ID. Includes a basic error handling structure. ```typescript import { JikanClient, JikanError } from 'myanimelist-wrapper'; const jikan = new JikanClient(); try { const anime = await jikan.anime.getById(5114); console.log(anime.data.title); } catch (error) { if (error instanceof JikanError) { console.error(`JikanError: ${error.message}`); } else { console.error('An unexpected error occurred'); } } ``` -------------------------------- ### Minimal JikanClient Configuration (Production) Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/configuration.md Instantiate JikanClient with default settings for production environments. No explicit configuration is needed. ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient(); // Uses all defaults ``` -------------------------------- ### Build and Test Project Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Build the project, run tests, and generate coverage reports using npm scripts. ```bash npm run build npm test npm run test:watch npm run test:coverage ``` -------------------------------- ### Get Anime Videos Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/anime-endpoint.md Fetches promotional videos and episode clips for a given anime ID. Requires the anime ID. ```typescript async getVideos(id: number): Promise> ``` -------------------------------- ### Quick Start: Fetch and Search Anime Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Initialize the JikanClient and use it to fetch anime by ID or search for anime. Includes basic error handling. ```typescript import { JikanClient } from 'myanimelist-wrapper'; // Initialize the client const jikan = new JikanClient(); // Fetch anime information const getAnime = async () => { try { const response = await jikan.anime.getById(5114); // Fullmetal Alchemist: Brotherhood console.log(response.data.title); console.log(response.data.score); } catch (error) { console.error('Error fetching anime:', error); } }; // Search for anime const searchAnime = async () => { try { const results = await jikan.anime.search({ q: 'attack on titan', limit: 5, type: 'tv' }); results.data.forEach(anime => { console.log(`${anime.title} (${anime.year})`); }); } catch (error) { console.error('Error searching anime:', error); } }; getAnime(); searchAnime(); ``` -------------------------------- ### Build Documentation Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/CONTRIBUTING.md Generate project documentation, likely using a tool like JSDoc or TypeDoc. Ensure documentation is up-to-date with changes. ```bash npm run docs ``` -------------------------------- ### Multi-Select Parameters Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Shows how to use comma-separated values for parameters like genres and producers to select multiple options. Also demonstrates excluding specific genres. ```typescript // Multiple genres await jikan.anime.search({ genres: '1,10,27' // Action, Fantasy, Shounen }); // Exclude genres await jikan.anime.search({ genres_exclude: '18' // Exclude Horror }); // Multiple producers await jikan.anime.search({ producers: '1,2,3' }); ``` -------------------------------- ### Get Anime Seasons Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Retrieve a list of anime seasons or specific seasons by year and season. Also includes methods to get current and upcoming seasons. ```typescript await jikan.seasons.getList() await jikan.seasons.getSeason(year, season) await jikan.seasons.getCurrent() await jikan.seasons.getUpcoming() ``` -------------------------------- ### Configure JikanClient Options Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Initialize the JikanClient with custom options such as base URL, timeout, and headers. This allows for advanced configuration. ```typescript const jikan = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 30000, headers: { 'User-Agent': 'MyApp/1.0' } }); ``` -------------------------------- ### Get User Watch/Read History Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/API.md Retrieves a user's history of watching anime or reading manga. Specify 'anime' or 'manga' to get the respective history. Useful for tracking user activity. ```typescript const history = await jikan.users.getHistory('firrthecreator', 'anime'); history.data.forEach(entry => { console.log(`${entry.entry.title}: +${entry.increment} episodes`); console.log(` Date: ${entry.date}`); }); ``` -------------------------------- ### Unit Testing JikanClient with Vitest Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/BEST-PRACTICES.md Demonstrates how to write unit tests for the JikanClient using Vitest, covering fetching anime by ID, handling not found errors, and searching anime. ```typescript import { describe, it, expect, beforeEach } from 'vitest'; import { JikanClient } from 'myanimelist-wrapper'; describe('JikanClient', () => { let client: JikanClient; beforeEach(() => { client = new JikanClient(); }); it('should fetch anime by ID', async () => { const response = await client.anime.getById(5114); expect(response.data).toBeDefined(); expect(response.data.mal_id).toBe(5114); expect(response.data.title).toBeDefined(); }); it('should handle not found errors', async () => { expect(async () => { await client.anime.getById(999999999); }).rejects.toThrow(); }); it('should search anime', async () => { const response = await client.anime.search({ q: 'naruto', limit: 5 }); expect(response.data).toBeInstanceOf(Array); expect(response.data.length).toBeLessThanOrEqual(5); }); }); ``` -------------------------------- ### Clone the Repository Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/CONTRIBUTING.md Clone your forked repository to your local machine. This is the first step after forking. ```bash git clone https://github.com/firrthecreator/myanimelist-wrapper.git ``` -------------------------------- ### Get Character Pictures Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieves pictures for a specific character. ```APIDOC ## Get Character Pictures ### Description Retrieves a list of pictures associated with a specific character. ### Method ```typescript jikan.characters.getPictures(characterId: number) ``` ### Parameters #### Path Parameters - **characterId** (number) - Required - The MyAnimeList ID of the character. ### Request Example ```typescript const pictures = await jikan.characters.getPictures(1); pictures.data.forEach(pic => { console.log(pic.jpg.image_url); }); ``` ### Response #### Success Response (200) - **data** (array) - An array of picture objects. - **jpg** (object) - Contains the URL for the JPG version of the picture. - **image_url** (string) - The URL of the character picture. ### Response Example ```json { "data": [ { "jpg": { "image_url": "https://cdn.myanimelist.net/images/characters/11/39585.jpg" } } ] } ``` ``` -------------------------------- ### Get Random Person Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches a single random person. ```typescript async getPerson(): Promise> ``` -------------------------------- ### Initialize JikanClient with Custom Options Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/README.md Configure the JikanClient with custom base URL, timeout, and headers. Ensure the 'Accept' header is set to 'application/json' for proper API communication. ```typescript import { JikanClient } from 'myanimelist-wrapper'; const jikan = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 30000, headers: { 'Accept': 'application/json' } }); ``` -------------------------------- ### Get Random Character Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches a single random character. ```typescript async getCharacter(): Promise> ``` -------------------------------- ### Get Random Manga Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches a single random manga. ```typescript async getManga(): Promise> ``` -------------------------------- ### Get Manga Characters Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieves characters associated with a given manga. ```APIDOC ## Get Manga Characters ### Description Retrieves a list of characters associated with a specific manga. ### Method ```typescript jikan.manga.getCharacters(mangaId: number) ``` ### Parameters #### Path Parameters - **mangaId** (number) - Required - The MyAnimeList ID of the manga. ### Request Example ```typescript const characters = await jikan.manga.getCharacters(1); characters.data.forEach(char => { console.log(`${char.character.name} (${char.role})`); }); ``` ### Response #### Success Response (200) - **data** (array) - An array of character objects associated with the manga. - **character** (object) - Information about the character. - **name** (string) - The name of the character. - **role** (string) - The role of the character in the manga (e.g., 'Main', 'Supporting'). ### Response Example ```json { "data": [ { "character": { "name": "Guts" }, "role": "Main" } ] } ``` ``` -------------------------------- ### Instantiate JikanClient Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Creates a new JikanClient instance. Optional configuration includes baseUrl, timeout, and custom headers. ```typescript new JikanClient() ``` -------------------------------- ### Get Anime Statistics Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieves viewing statistics for a given anime. ```APIDOC ## Get Anime Statistics ### Description Retrieves viewing statistics for a specific anime, such as the number of users who have watched, watching, or plan to watch it. ### Method ```typescript jikan.anime.getStatistics(animeId: number) ``` ### Parameters #### Path Parameters - **animeId** (number) - Required - The MyAnimeList ID of the anime. ### Request Example ```typescript const stats = await jikan.anime.getStatistics(5114); stats.data.forEach(stat => { console.log(`${stat.title}: ${stat.count} users`); }); ``` ### Response #### Success Response (200) - **data** (array) - An array of statistics objects. - **title** (string) - The type of statistic (e.g., 'Watching', 'Completed'). - **count** (number) - The number of users for that statistic. ### Response Example ```json { "data": [ { "title": "Watching", "count": 150000 }, { "title": "Completed", "count": 1200000 } ] } ``` ``` -------------------------------- ### Get Random User Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches a single random user profile. ```typescript async getUser(): Promise> ``` -------------------------------- ### Get All Available Seasons Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Retrieves a list of all seasons available in the database. ```typescript async getList(): Promise> ``` -------------------------------- ### Get Person Pictures Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches the picture gallery for a specific person. ```typescript async getPictures(id: number): Promise> ``` -------------------------------- ### JikanClient Configuration Immutability Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/configuration.md Demonstrates that JikanClient configuration is immutable after instantiation. To change settings, a new client instance must be created. ```typescript // Wrong - client1 settings are immutable const client1 = new JikanClient({ timeout: 30000 }); // client1.timeout = 60000; // Not possible // Correct - create a new client const client2 = new JikanClient({ timeout: 60000 }); ``` -------------------------------- ### Search Documentation with Grep Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/INDEX.md Use grep commands to efficiently search for specific information within the documentation files, such as method signatures, type definitions, error codes, examples, and parameter descriptions. ```bash grep -n "async " anime-endpoint.md ``` ```bash grep -n "^### " types.md ``` ```bash grep -n "^###.*[0-9][0-9][0-9]" errors.md ``` ```bash grep -n "Example:" *.md ``` ```bash grep -n "| Parameter" *.md ``` -------------------------------- ### Get Character Pictures Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches the picture gallery for a specific character. ```typescript async getPictures(id: number): Promise> ``` -------------------------------- ### Instantiate JikanClient with Options Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Creates a new JikanClient instance with custom configuration options for API requests. ```typescript new JikanClient({ baseUrl: "https://api.jikan.moe/v4", timeout: 10000, headers: { "X-Custom-Header": "value" } }) ``` -------------------------------- ### Get Anime and Manga Reviews Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Fetch reviews for anime and manga. ```typescript await jikan.reviews.getAnimeReviews() await jikan.reviews.getMangaReviews() ``` -------------------------------- ### Default Client and Pagination Options Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Shows the default configuration options for the client, including base URL, timeout, headers, and pagination settings. ```typescript // Client options { baseUrl: 'https://api.jikan.moe/v4', timeout: 30000, // 30 seconds headers: { 'Accept': 'application/json' } } // Pagination { page: 1, limit: 25 } // Sort { sort: 'desc' } ``` -------------------------------- ### Get Anime Staff Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/anime-endpoint.md Retrieves the production staff involved in an anime. ```APIDOC ## GET /anime/{id}/staff ### Description Get anime production staff (directors, composers, etc.). ### Method GET ### Endpoint `/anime/{id}/staff` #### Path Parameters - **id** (number) - Required - Anime ID ### Response #### Success Response (200) - **data** (Array) - Array of staff members with positions ``` -------------------------------- ### Get Random Anime Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Fetch a single random anime entry. ```typescript // Get random content const randomAnime = await jikan.random.getAnime(); ``` -------------------------------- ### Get Top Manga Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieves a list of top-rated manga, with filtering options. ```APIDOC ## Get Top Manga ### Description Retrieves a list of top-rated manga based on user scores, with options for filtering and pagination. ### Method ```typescript jikan.top.getManga(options: { filter?: 'publishing' | 'upcoming' | 'bypopularity' | 'favorite'; limit?: number; page?: number; }) ``` ### Parameters #### Query Parameters - **filter** (string) - Optional - The filter for top manga (e.g., 'publishing', 'upcoming'). - **limit** (number) - Optional - The maximum number of results to return. - **page** (number) - Optional - The page number for pagination. ### Request Example ```typescript const topManga = await jikan.top.getManga({ filter: 'publishing', limit: 10 }); topManga.data.forEach((manga, index) => { console.log(`${index + 1}. ${manga.title} - ${manga.score}`); }); ``` ### Response #### Success Response (200) - **data** (array) - An array of top manga objects. - **title** (string) - The title of the manga. - **score** (number) - The score of the manga. ### Response Example ```json { "data": [ { "title": "Berserk", "score": 9.5 } ] } ``` ``` -------------------------------- ### Project Scripts Defined in package.json Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Overview of available npm scripts for building, cleaning, linting, formatting, testing, and generating documentation. ```json { "scripts": { "build": "tsc", // Compile TypeScript "clean": "rimraf dist", // Clean build directory "lint": "eslint . --fix", // Lint and fix code "format": "prettier --write", // Format code "test": "vitest run", // Run tests once "test:watch": "vitest", // Watch tests "test:coverage": "vitest run --coverage", "docs": "typedoc --out docs src/index.ts", "prepare": "husky install" } } ``` -------------------------------- ### Get Top Anime Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/README.md Retrieves a list of top-rated anime, with filtering options. ```APIDOC ## Get Top Anime ### Description Retrieves a list of top-rated anime based on user scores, with options for filtering and pagination. ### Method ```typescript jikan.top.getAnime(options: { filter?: 'airing' | 'upcoming' | 'bypopularity' | 'favorite'; limit?: number; page?: number; }) ``` ### Parameters #### Query Parameters - **filter** (string) - Optional - The filter for top anime (e.g., 'airing', 'upcoming'). - **limit** (number) - Optional - The maximum number of results to return. - **page** (number) - Optional - The page number for pagination. ### Request Example ```typescript const topAnime = await jikan.top.getAnime({ filter: 'airing', limit: 25, page: 1 }); topAnime.data.forEach((anime, index) => { console.log(`${index + 1}. ${anime.title} - ${anime.score}`); }); ``` ### Response #### Success Response (200) - **data** (array) - An array of top anime objects. - **title** (string) - The title of the anime. - **score** (number) - The score of the anime. ### Response Example ```json { "data": [ { "title": "Fullmetal Alchemist: Brotherhood", "score": 9.1 } ] } ``` ``` -------------------------------- ### Run Tests Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/CONTRIBUTING.md Execute the project's test suite to ensure your changes do not introduce regressions. This should be run before committing. ```bash npm test ``` -------------------------------- ### Get Manga Recommendations Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches recent manga recommendations. Supports pagination. ```typescript async getMangaRecommendations( params?: RecommendationQueryParams ): Promise> ``` -------------------------------- ### Initialize JikanClient with Custom Base URL Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/configuration.md Configure JikanClient to use a custom API instance, such as a proxy or alternative server. ```typescript // Use a custom instance const jikanProxy = new JikanClient({ baseUrl: 'https://api.example.com/jikan/v4' }); ``` -------------------------------- ### Get Anime Recommendations Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/additional-endpoints.md Fetches recent anime recommendations. Supports pagination. ```typescript async getAnimeRecommendations( params?: RecommendationQueryParams ): Promise> ``` -------------------------------- ### Get Anime Characters Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/API.md Retrieves a list of all characters associated with a specific anime. ```APIDOC ## GET /anime/{id}/characters ### Description Get all characters in an anime. ### Method GET ### Endpoint `/anime/{id}/characters` ### Parameters #### Path Parameters - **id** (number, required): Anime ID ### Response #### Success Response (200) - **data** (array): Array of character objects for the anime. ### Response Structure ```typescript interface AnimeCharacter { character: { mal_id: number; name: string; images: Images; url: string; }; role: string; // Main, Supporting, Background voice_actors: VoiceActor[]; } interface VoiceActor { person: { mal_id: number; name: string; images: Images; url: string; }; language: string; // "Japanese", "English", etc. } ``` ### Request Example ```typescript const characters = await jikan.anime.getCharacters(5114); characters.data.forEach(char => { console.log(`${char.character.name} (${char.role})`); if (char.voice_actors.length > 0) { const japaneseVA = char.voice_actors.find(va => va.language === 'Japanese'); if (japaneseVA) { console.log(` VA (JP): ${japaneseVA.person.name}`); } } }); ``` ### Response Example ```json { "data": [ { "character": { "mal_id": 1, "name": "Edward Elric", "url": "...", "images": {"jpg": {"image_url": "..."}} }, "role": "Main", "voice_actors": [ { "person": {"mal_id": 123, "name": "Romi Park", "url": "...", "images": {"jpg": {"image_url": "..."}}}, "language": "Japanese" }, { "person": {"mal_id": 456, "name": "Vic Mignogna", "url": "...", "images": {"jpg": {"image_url": "..."}}}, "language": "English" } ] } ] } ``` ``` -------------------------------- ### Initialize JikanClient with Default Base URL Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/configuration.md Instantiate JikanClient using the default official API endpoint. ```typescript // Use default official API const jikan = new JikanClient(); ``` -------------------------------- ### Get Anime and Manga Genres Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/quick-reference.md Fetch lists of genres for both anime and manga. ```typescript await jikan.genres.getAnimeGenres() await jikan.genres.getMangaGenres() ``` -------------------------------- ### Sorting Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Demonstrates how to sort search results using the 'order_by' and 'sort' parameters. Shows sorting by score in descending order and by popularity in ascending order. ```typescript // Sort by score, highest first await jikan.anime.search({ q: 'romantic', order_by: 'score', sort: 'desc' }); // Sort by popularity, least popular first await jikan.anime.search({ order_by: 'popularity', sort: 'asc' }); ``` -------------------------------- ### Get Anime Episodes Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/anime-endpoint.md Fetches a paginated list of episodes for a specific anime. ```APIDOC ## GET /anime/{id}/episodes ### Description Get paginated list of episodes for an anime. ### Method GET ### Endpoint `/anime/{id}/episodes` #### Path Parameters - **id** (number) - Required - Anime ID #### Query Parameters - **page** (number) - Optional - Page number for pagination (default: 1) ### Response #### Success Response (200) - **data** (Array) - Paginated episodes - **pagination** (object) - Pagination information ### Request Example ```typescript const episodes = await jikan.anime.getEpisodes(5114, 1); ``` ``` -------------------------------- ### Get Anime by ID Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/anime-endpoint.md Fetches complete anime information by its MyAnimeList ID. ```APIDOC ## GET /anime/{id} ### Description Fetches complete anime information by ID. ### Method GET ### Endpoint `/anime/{id}` #### Path Parameters - **id** (number) - Required - MyAnimeList anime ID ### Response #### Success Response (200) - **data** (Anime) - Anime object with full details ### Request Example ```typescript const response = await jikan.anime.getById(5114); console.log(response.data.title); ``` ``` -------------------------------- ### Initialize JikanClient Globally Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/docs/INSTALLATION.md Initialize the JikanClient with a base URL and timeout. This is typically done once and exported for use across your application. ```typescript import { JikanClient } from 'myanimelist-wrapper'; export const jikan = new JikanClient({ baseUrl: 'https://api.jikan.moe/v4', timeout: 30000 }); ``` -------------------------------- ### Create Multiple Client Instances Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/configuration.md Initialize multiple JikanClient instances with different configurations, such as varying timeouts or base URLs, to manage different request behaviors. ```typescript // Create multiple clients with different configurations const clients = { default: new JikanClient(), fast: new JikanClient({ timeout: 5000 }), slow: new JikanClient({ timeout: 120000 }), proxy: new JikanClient({ baseUrl: 'https://proxy.example.com/jikan/v4' }) }; // Use appropriate client for each request const animeData = await clients.default.anime.getById(5114); const fastResult = await clients.fast.anime.search({ q: 'naruto', limit: 1 }); ``` -------------------------------- ### Get User Profile Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Retrieve a user's profile information by their username. ```typescript // Get user profile const user = await jikan.users.getByUsername('firrthecreator'); ``` -------------------------------- ### Get Seasonal Anime Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Fetch a list of anime for a specific season and year. ```typescript // Get seasonal anime const winterAnime = await jikan.seasons.getSeason(2024, 'winter'); ``` -------------------------------- ### Search Anime with Query Parameters Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Demonstrates how to search for anime using specific query parameters like limit, order_by, sort, and sfw. Provides a reasonable limit and sorts results by score in descending order. ```typescript async function searchAnime(query: string) { const results = await jikan.anime.search({ q: query, limit: 10, // Reasonable limit order_by: 'score', // Best matches first sort: 'desc', sfw: true // Optional: safe for work }); return results.data; } ``` -------------------------------- ### JikanClient Constructor Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/jikan-client.md Creates a new JikanClient instance with optional configuration for the Jikan API v4. ```APIDOC ## Constructor JikanClient ### Description Creates a new JikanClient instance with optional configuration. ### Method `constructor(options?: JikanClientOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const client = new JikanClient({ timeout: 10000 }); ``` ### Response None ### Options - **baseUrl** (`string`, Optional, Default: `https://api.jikan.moe/v4`) - Base URL for the Jikan API. - **timeout** (`number`, Optional, Default: `30000`) - Request timeout in milliseconds. - **headers** (`Record`, Optional, Default: `{}`) - Custom HTTP headers to include in all requests. ``` -------------------------------- ### Club Filtering Example Source: https://github.com/firrthecreator/myanimelist-wrapper/blob/main/_autodocs/query-parameters.md Illustrates filtering club search results by category and type. ```typescript // Club filters await jikan.clubs.search({ category: 'anime', type: 'public' }); ```