### Initialize Yahoo Fantasy Module (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Demonstrates how to initialize the Yahoo Fantasy module with application credentials and optional callback functions for token refreshes and redirect URIs. This setup is essential for authenticating API requests. ```javascript const YahooFantasy = require('yahoo-fantasy'); const yf = new YahooFantasy( Y!APPLICATION_KEY, // Yahoo! Application Key Y!APPLICATION_SECRET, // Yahoo! Application Secret tokenCallbackFunction, // callback function when user token is refreshed (optional) redirectUri // redirect endpoint when user authenticates (optional) ); ``` -------------------------------- ### Handle Yahoo API Authentication Callback (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Illustrates the setup of the callback route to handle the authentication code received from Yahoo!. This function automatically sets the user and refresh tokens upon successful retrieval. ```javascript yf.authCallback( request, // the request will contain the auth code from Yahoo! callback // callback function that will be called after the token has been retrieved ) ``` -------------------------------- ### Update League Resource for Player Stats Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md A 'players' subresource has been added to the 'league' resource. This allows for fetching weekly or season stats for a player based on league settings. This also includes fixes for data format shifts affecting starting status. ```javascript async function getLeaguePlayerStats(leagueKey, playerKey, seasonType = 'season', week = null) { let url = `/league/${leagueKey}/players;{playerKey}/stats`; if (seasonType === 'week' && week) { url += `?week=${week}`; } else if (seasonType === 'season') { // Default season stats query } // Assuming 'this' context is the API client with a 'request' method return this.request(url); } ``` -------------------------------- ### Query Resource/Subresource with Promises (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Shows how to query Yahoo Fantasy API resources and subresources using a promise chain, available from v3.1.0. This allows for cleaner asynchronous code with `.then()` for success and `.catch()` for errors. ```javascript yf.{resource}.{subresource} ( {possible argument(s)} ) .then(data => // do your thing) .catch(err => // handle error) ``` -------------------------------- ### Query Resource/Subresource with Async/Await (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Illustrates querying Yahoo Fantasy API resources and subresources using the `async/await` syntax, supported in newer versions of Node.js. This provides a synchronous-like way to handle asynchronous operations, including robust error handling with `try...catch`. ```javascript try { let data = await yf.{resource}.{subresource} ( {possible argument(s)} ) // do your thing } catch(err) { // handle error } ``` -------------------------------- ### Query Resource/Subresource with Callback (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Demonstrates how to query specific resources and subresources of the Yahoo Fantasy API using a traditional callback pattern. It includes error handling and processing of the returned data. ```javascript yf.{resource}.{subresource} ( {possible argument(s)}, function cb(err, data) { // handle error // callback function // do your thing } ); ``` -------------------------------- ### Authenticate User with Yahoo API (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Shows how to initiate the user authentication process by redirecting the user to Yahoo!'s login screen. This is typically done by calling the `auth` method with the response object. ```javascript yf.auth( response // response object to redirect the user to the Yahoo! login screen ) ``` -------------------------------- ### Use Promise-Based Flow for Endpoints Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md This update introduces a promise-based flow for all API endpoints, offering an alternative to traditional callbacks. This improves asynchronous code handling and readability. ```javascript class YahooFantasyApiClient { // ... constructor and other methods ... request(endpoint) { return new Promise((resolve, reject) => { // Replace with actual fetch or axios implementation fetch(`https://fantasysports.yahooapis.com/fantasy/v2${endpoint}`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => resolve(data)) .catch(error => reject(error)); }); } // Example usage of a promise-based endpoint getGameLeagues(gameKey) { return this.request(`/game/${gameKey}/leagues`); } } // Usage: const yahooApi = new YahooFantasyApiClient(/* ... */); yahooApi.getGameLeagues('397') .then(leagues => console.log(leagues)) .catch(error => console.error('Error fetching leagues:', error)); ``` -------------------------------- ### Add Authentication Functions (auth, authCallback, setRefreshToken) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md This version introduces new functions for authentication: `auth()` for initiating the OAuth flow, `authCallback()` for handling the redirect response, and `setRefreshToken()` for managing refresh tokens. It also adds automatic token refreshing and a callback for when the token expires. ```javascript class YahooFantasyAuth { constructor(clientId, clientSecret, redirectUri) { this.clientId = clientId; this.clientSecret = clientSecret; this.redirectUri = redirectUri; this.refreshToken = null; this.accessToken = null; } auth() { const authUrl = `https://api.login.yahoo.com/oauth2/request_auth?client_id=${this.clientId}&redirect_uri=${this.redirectUri}&response_type=code`; window.location.href = authUrl; } async authCallback(code) { const tokenEndpoint = 'https://api.login.yahoo.com/oauth2/get_token'; const params = new URLSearchParams(); params.append('client_id', this.clientId); params.append('client_secret', this.clientSecret); params.append('redirect_uri', this.redirectUri); params.append('code', code); params.append('grant_type', 'authorization_code'); const response = await fetch(tokenEndpoint, { method: 'POST', body: params }); const data = await response.json(); this.accessToken = data.access_token; this.refreshToken = data.refresh_token; return data; } setRefreshToken(refreshToken) { this.refreshToken = refreshToken; } // Method to automatically refresh token (implementation details omitted) async refreshTokenIfNeeded() { // ... logic to check expiration and refresh using this.refreshToken ... } } ``` -------------------------------- ### Set Yahoo User Token Manually (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Provides a method to manually set the Yahoo! user token if authentication is not handled directly by the library. This is useful for pre-authenticated sessions or custom auth flows. ```javascript yf.setUserToken( Y!CLIENT_TOKEN ); ``` -------------------------------- ### Refactor to ES Modules (mjs) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md The library has undergone a major refactor using ES Modules (mjs) where possible. This modernization aims to improve code organization and compatibility with modern JavaScript environments. ```javascript // Example of an ES Module file (e.g., './auth.mjs') // Import other modules if needed // import { someUtil } from './utils.mjs'; export async function auth(clientId, redirectUri) { const authUrl = `https://api.login.yahoo.com/oauth2/request_auth?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`; window.location.href = authUrl; } export async function authCallback(clientId, clientSecret, redirectUri, code) { const tokenEndpoint = 'https://api.login.yahoo.com/oauth2/get_token'; const params = new URLSearchParams(); params.append('client_id', clientId); params.append('client_secret', clientSecret); params.append('redirect_uri', redirectUri); params.append('code', code); params.append('grant_type', 'authorization_code'); const response = await fetch(tokenEndpoint, { method: 'POST', body: params }); return await response.json(); } // Usage in another ES Module file (e.g., './main.mjs') // import { auth, authCallback } from './auth.mjs'; // async function initiateAuth() { // const clientId = 'YOUR_CLIENT_ID'; // const redirectUri = 'YOUR_REDIRECT_URI'; // auth(clientId, redirectUri); // } // async function handleCallback() { // const urlParams = new URLSearchParams(window.location.search); // const code = urlParams.get('code'); // if (code) { // const clientId = 'YOUR_CLIENT_ID'; // const clientSecret = 'YOUR_CLIENT_SECRET'; // const redirectUri = 'YOUR_REDIRECT_URI'; // const tokenData = await authCallback(clientId, clientSecret, redirectUri, code); // console.log('Access Token:', tokenData.access_token); // console.log('Refresh Token:', tokenData.refresh_token); // } // } ``` -------------------------------- ### Update mapScoreboard Function for League Resource Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md This update simplifies the `stat_winners` array within the `mapScoreboard` function, which is used by the league resource. It now directly shows the winning `stat_id` and `team_key` (or `is_tied`) instead of nesting them within a `stat_winner` object. ```javascript function mapScoreboard() { // ... existing code ... const simplifiedStatWinners = league.scoreboard.stats.map(stat => { // Assuming stat_winners is an array of objects like [{ stat_winner: { stat_id: '...', team_key: '...' } }] // The change implies it might now be an array of objects like [{ stat_id: '...', team_key: '...' }] return stat.stat_winners.map(winnerWrapper => { if (winnerWrapper.stat_winner.is_tied) { return { stat_id: winnerWrapper.stat_winner.stat_id, is_tied: true }; } else { return { stat_id: winnerWrapper.stat_winner.stat_id, team_key: winnerWrapper.stat_winner.team_key }; } }); }); // ... rest of the function potentially using simplifiedStatWinners ... } ``` -------------------------------- ### Update authCallback Function Return Value Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md The `authCallback()` function now returns an object containing both the user's `access_token` and `refresh_token`. This provides more comprehensive authentication information upon successful callback. ```javascript async function handleAuthCallback(authCode) { // ... authentication logic ... const response = await fetch('/oauth2/token', { method: 'POST', // ... other options ... body: `code=${authCode}&grant_type=authorization_code` }); const data = await response.json(); return { accessToken: data.access_token, refreshToken: data.refresh_token }; } ``` -------------------------------- ### Set Yahoo Refresh Token Manually (Node.js) Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md Enables manual setting of the Yahoo! refresh token. When set, the library can automatically refresh the access token if it expires, utilizing the provided `tokenCallbackFunction` to persist the new token. ```javascript yf.setRefreshToken( Y!CLIENT_REFRESH_TOKEN ); ``` -------------------------------- ### Update player.stats Function for Week or Date Input Source: https://github.com/whatadewitt/yahoo-fantasy-sports-api/blob/master/README.md The `player.stats` function has been updated to accept either a week number or a date string in 'yyyy-mm-dd' format as the second parameter. This enhances flexibility when querying player statistics. Note: For non-NFL players, manual week fetching and multiple queries might be necessary. ```javascript async function getPlayerStats(playerKey, weekOrDate) { let queryParams = ''; if (typeof weekOrDate === 'number') { queryParams = `?week=${weekOrDate}`; } else if (typeof weekOrDate === 'string' && /\\d{4}-\\d{2}-\\d{2}/.test(weekOrDate)) { queryParams = `?date=${weekOrDate}`; } else { throw new Error('Invalid week or date format'); } // Assuming 'this' context is the API client with a 'request' method return this.request(`/players;{playerKey}/stats${queryParams}`); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.