Kayn
superagent-inspired Node.js lib (w/ **some** TypeScript support) for accessing Riot's League of Legend's API (discord: cnguy#3614)
Install / Use
/learn @cnguy/KaynREADME
A small Node.js library to work with Riot's League of Legend's API.
<details><summary>Simple example using promises and callbacks</summary> <p>const _kayn = require('kayn')
const Kayn = _kayn.Kayn
const REGIONS = _kayn.REGIONS
const kayn = Kayn(/* process.env.RIOT_LOL_API_KEY */)(/* optional config */)
kayn.Summoner.by
.name('Contractz')
.region(REGIONS.NORTH_AMERICA) // same as 'na'
.callback(function(unhandledError, summoner) {
kayn.Matchlist.by
.accountID(summoner.accountId)
/* Note that region falls back to default if unused. */
.query({
season: 11,
queue: [420, 440],
})
.then(function(matchlist) {
console.log('actual matches:', matchlist.matches)
console.log('total number of games:', matchlist.totalGames)
})
.catch(console.error)
})
</p>
</details>
<details><summary>Same example (as the above) using async/await, destructuring, and template strings</summary>
<p>
import { Kayn, REGIONS } from 'kayn'
const kayn = Kayn(/* process.env.RIOT_LOL_API_KEY */)(/* optional config */)
const main = async () => {
const { accountId } = await kayn.Summoner.by.name('Contractz')
// ^ default region is used, which is `na` unless specified in config
const { matches, totalGames } = await kayn.Matchlist.by
.accountID(accountId)
.query({ season: 11, champion: 67 })
.region(REGIONS.NORTH_AMERICA)
console.log('actual matches:', matches)
console.log(`total number of games: ${totalGames}`)
}
main()
</p>
</details>
<details><summary>Example of getting match information from 100 matches at once</summary>
<p>
const getChampionIdFromMatch = (match, accountId) => {
for (let i in match.participantIdentities) {
if (
match.participantIdentities[i].player.currentAccountId ===
accountId
) {
return match.participants[parseInt(i)].championId
}
}
}
const main = async kayn => {
const { accountId } = await kayn.SummonerV4.by.name('Contractz')
const rankGameIds = (await kayn.MatchlistV4.by
.accountID(accountId)
.query({ queue: 420 })).matches.map(el => el.gameId)
const championIds = await Promise.all(
rankGameIds.map(async gameId => {
const matchDetail = await kayn.MatchV4.get(gameId).region('na')
return getChampionIdFromMatch(matchDetail, accountId)
}),
)
console.log(championIds.slice(0, 5), championIds.length)
}
</p>
</details>
<details><summary>Example of getting DDragon information of banned champions in a game</summary>
<p>
const main = async (kayn) => {
const match = await kayn.Match.get(2877485196)
const bans = match.teams.map(m => m.bans).reduce((t, c) => t.concat(c), [])
const ids = bans.map(b => b.championId)
const ddragonChampions = await kayn.DDragon.Champion.listDataByIdWithParentAsId()
const champions = ids.map(id => ddragonChampions.data[id])
console.log(champions)
}
</p>
</details>
<details><summary>Example Selected Implementations</summary>
<p>
- Get last 10 matches asynchronously and efficiently (vs slower version as well)
- Get champion name, win status, season id, and game date for past 5 ranked games of a player
... More Examples
</p> </details>Table of Contents:
- Features
- Methods
- Installation & (Riot API) Usage
- DDragon Usage
- Configuration
- My Project
- Bugs / Changelog / Disclaimer
- FAQ
Features
Rate Limiting
Handled by Colorfulstan's wonderful riot-ratelimiter.
See RATELIMITING.md.
All Endpoints Covered
Caching
Currently supports a basic JS cache (for simple scripts), node-lru-cache, and Redis.
Compatible with Callbacks, Promises, Async / Await
TypeScript Support
Works immediately upon installation.
As of v0.8.0, full DTO's are provided thanks to MingweiSamuel's auto-updated Swagger JSON.
Methods
Check out ENDPOINTS.md to see kayn's methods, as well as the endpoints covered.
Documentation
The auto-generated ESDoc documentation can be found here.
Installation and Usage
The minimum required Node.js version is v7.6.0 for native async/await support (there's only a mere line in the codebase, though).
npm
npm i --save kayn
yarn
yarn add kayn
Quick Setup with Default Config
const { Kayn, REGIONS } = require('kayn')
const kayn = Kayn('RGAPI-my-api-key')(/*{
region: REGIONS.NORTH_AMERICA,
apiURLPrefix: 'https://%s.api.riotgames.com',
locale: 'en_US',
debugOptions: {
isEnabled: true,
showKey: false,
},
requestOptions: {
shouldRetry: true,
numberOfRetriesBeforeAbort: 3,
delayBeforeRetry: 1000,
burst: false,
shouldExitOn403: false,
},
cacheOptions: {
cache: null,
timeToLives: {
useDefault: false,
byGroup: {},
byMethod: {},
},
},
}*/)
Note: Any config passed in is deeply merged with the default config.
Environment Variables
const kayn = Kayn(/* process.env.RIOT_LOL_API_KEY */)(myConfig)
Although it is possible to manually pass in the API key, it is preferable to store the key in a secret file (which should not be committed).
This allows kayn to be constructed like in the above code.
# filename: .env
RIOT_LOL_API_KEY=RGAPI-my-api-key
Callbacks
kayn.Summoner.by.name('Contractz').callback(function(err, summoner) {
// do something
})
Promises
kayn.Summoner.by.name('Contractz')
.then(summoner => doSomething(summoner))
.then(console.log)
.catch(error => console.error(error))
Async / Await
const main = async () => {
const ctz = await kayn.Summoner.by.name('Contractz')
}
Region
This forces a request to target a specific region instead of the default region set in kayn's config. If .region() is not used, kayn will use the default region to make requests.
kayn.Summoner.by.name('hide on bush')
.region(REGIONS.KOREA)
.callback(function(error, summoner) {
doSomething(summoner)
})
Region without Throwing
There is another utility method in case if you want to avoid handling exceptions caused by .region(). This method simply catches .region()'s exception, and so it will fall back to the default region as well.
kayn.Summoner.by.name('hide on bush')
.regionNoThrow(null) // No error thrown. Uses default region.
kayn.Summoner.by.name('hide on bush')
.regionNoThrow(3) // Same as above.
kayn.Summoner.by.name('hide on bush')
.regionNoThrow('kr524') // Same as above.
Query Parameters
You can pass in strings, numbers, or arrays as values. Just pass in whatever Riot expects. :)
kayn.Matchlist.by.accountID(3440481)
.region(REGIONS.KOREA)
.query({
season: 9,
queue: [420, 440],
})
.callback(function(err, matchlist) {
console.log(matchlist.matches.length)
})
Request Errors
Errors as of v0.8.7 return the following error object:
{
statusCode: 42, // some random number
url: '', // the debug URL that is used in logging as well
error: {} // the rest of the error object
}
DDragon Usage
Version
This forces a request to target a specific version and is no longer mandatory as of v0.8.22.
kayn.DDragon.Champion.list()
.version('8.15.1') /* Explicit */
.callback(function(error, champions) {
console.log(champions)
})
// Let's say the config region is North America and that the latest version
// for the champion endpoint in NA is 8.24.1
kayn.DDragon.Champion.list() // Implicitly targets 8.24.1
.callback(function(error, champions) {
console.log(champions)
})
// Same thing as above, but gets the versions for a different region from the configuration.
kayn.DDragon.Champion.list().region('br')
.callback(function(error, champions) {
console.log(champions)
})
Notes about Optional Version Argument
Whenever you make a request that does not have a version passed in, kayn will automatically grab all the JSON versions associated with your default region or through the region() method.
If you do not have caching enabled, note that each request with no version passed will always send an additional


