Giter Site home page Giter Site logo

gw2api-client's Introduction

gw2api-client

Build Status Coverage Status Greenkeeper badge Bundle Size

Javascript wrapper for the official Guild Wars 2 API.

Install

npm install gw2api-client

This module can be used for Node.js as well as browsers using Browserify.

Usage

Basic usage

const client = require('gw2api-client')

// Get an instance of an API client
let api = client()

// Optional, but recommended: Set the schema version of the client
api.schema('2019-03-26T00:00:00Z')

// Optional: Set the language of the client
api.language('en')

// Optional: Authenticate the client using an API key
api.authenticate('my-secret-key')

// Get the ids of all items
api.items().ids().then(items => console.log(items))

// Get a single item
api.items().get(123).then(item => console.log(item))

// Get multiple items
api.items().many([123, 456]).then(items => console.log(items))

// Get all items
api.items().all().then(items => console.log(items))

Endpoints

You can find all endpoints and their respective function calls in this document.

Caching

You can find all cache storages (and the interface for custom ones) in this document.

By default, calling any endpoint requests data from the live API. However, you can easily enable caching for all appropriate endpoints by giving the client a cache storage to work with. You can find the default cache times of all endpoints here.

const cacheMemory = require('gw2api-client/src/cache/memory')
api.cacheStorage(cacheMemory())

// This will only call the official API once
api.items().ids()
// ...
api.items().ids()

// When the cache expires, this will call the official API again
api.items().ids()

// You can skip the cache for guaranteed live data
api.items().live().ids()

Note: The cache storage save is asynchronous in the background. During this time, the API function already resolves a result for best performance. Therefore it can happen that some data gets requested twice, if you request it in rapid succession and are not using a cache that saves in memory (memory or browser caches).

You can also chain multiple cache storages together. In this case, the cache gets saved in all storages and read from the first storage in the list answering with a valid value. The more persistent and more reliable cache storages should therefore be on the end of the list and the fastest (e.g. memory) should be at the start of the list.

const cacheMemory = require('gw2api-client/src/cache/memory')
const cacheRedisStorage = require('gw2api-client/src/cache/redis')

// Save in memory and local storage
// Try to answer from memory first, then from local storage and then hit the API
api.cacheStorage([
  cacheMemory(),
  cacheRedisStorage({ ... })
])

The cache uses expiration times and not the build number, because the content of the API can update independently of the build id. This is caused by the internal whitelisting of the API. However, if you want your cache to invalidate when there is a game update, this is easily possible too:

// configure api.cacheStorage(...) beforehand

// Check the build every 10 minutes and flush the cache if it updated
setInterval(() => api.flushCacheIfGameUpdated(), 10 * 60 * 1000)

Error handling

You can use the Promise catch to handle all possible errors.

api.account().bank().catch(err => {
  // err.response is the last response object (e.g. err.response.status)
  // err.content is the parsed body of the response, if available
  // err.content.text is the error text thrown of the API, if available
  console.error('Something went wrong', err)
})

The API can throw server errors (status >= 500) that don't have a text property set. However, most of the time it responds with one of the following errors:

  • endpoint requires authentication
  • invalid key
  • requires scope <xyz>
  • membership required
  • access restricted to guild leaders
  • page out of range
  • no such id
  • all ids provided are invalid

Retrying

By accessing the fetch instance, you can enable retrying in case the API or the user has problems getting a valid response. You can find the full documentation for retrying here.

// Retry up to 3 times if the status indicates an request error
api.fetch.retry((tries, err) => {
  if (tries > 3) { 
    return false
  }

  const res = err.response
  if (res && (res.status < 400 || res.status === 403)) {
    return false
  }

  return true
})

// Wait in between retries
api.fetch.retryWait((tries) => tries * 100)

// This request will now retry if it fails (e.g. API issues)
api.items().ids()

Extending

You can extend or overwrite the API client with your own endpoints if you wish so. The only thing that is required is an extension of AbstractEndpoint to provide all the logic for pagination, bulk, localisation, caching and so on.

If you need more specific ways to handle data then the already defined ones, take a look at how the existing endpoints handle these edge cases (e.g. in /src/endpoints/recipes.js).

const client = require('gw2api-client')
const AbstractEndpoint = require('gw2api-client/src/endpoint')

// Get an instance of an API client
const api = client()

// Example: Add a new function inside the abstract endpoint
AbstractEndpoint.prototype.post = function () {
  console.log(this)
}

// Example: Define our custom "items" endpoint
class ItemsEndpoint extends AbstractEndpoint {
  constructor (client) {
    super(client)
    this.baseUrl = 'https://api.my-domain.com'
    this.url = '/items'
    this.isPaginated = false
    this.isBulk = true
    this.supportsBulkAll = false
    this.isLocalized = true
    this.cacheTime = 5 * 60

    // Send credentials (e.g. session cookies)
    this.credentials = true
  }
}

// Attach it to the client, either as a new endpoint or overwriting an already existing one
api.items = () => new ItemsEndpoint(api)

// Use the new, overwritten endpoint
api.items().many([123, 456])
  .then(items => console.log('Got the items', items))
  .catch(err => console.error('Things went badly', err))

Mocking

If you want to mock this module in your tests, you can replace the underlying lets-fetch library with the provided mock module, e.g. using rewire. You can find all available mock methods here.

const fetchMock = require('lets-fetch/mock')
const file = require('./some/file/using/gw2api/client.js')

// Get the variable "api" (which would be the initialized api client
// in your own code) and replace the fetch method with the fetchMock
file.__get__('api').fetch = fetchMock

// Use the fetch mock methods as described in the link above

Debugging

You can enable debug messages by setting a flag on the client:

const client = require('gw2api-client')
let api = client()

// Set for specific endpoints
let items = api.items().debugging(true).ids().then(items => console.log(items))

// Set for all endpoints
api.debugging(true).items().ids().then(items => console.log(items))

Tests

npm test

Licence

MIT

gw2api-client's People

Contributors

archomeda avatar darthmaim avatar greenkeeper[bot] avatar marcustyphoon avatar queicherius avatar rikkuness avatar themrmilchmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gw2api-client's Issues

Handle api key / language assigning better

Right now, you have to generate a completely fresh client if you want to run two requests with different languages or API keys in parallel, which is a bit sub-optimal.

An in-range update of lets-fetch is breaking the build 🚨

The dependency lets-fetch was updated from 2.1.0 to 2.1.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

lets-fetch is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 4 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @emotion/hash is breaking the build 🚨

The dependency @emotion/hash was updated from 0.7.0 to 0.7.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@emotion/hash is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @emotion/hash is breaking the build 🚨

The dependency @emotion/hash was updated from 0.7.3 to 0.7.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@emotion/hash is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Generate the `endpoints.md` out of source comments

Something ala:

/**
 * Information about the available world bosses.
 *
 * Usage: `api().worldbosses()`
 */
class WorldbossesEndpoint extends AbstractEndpoint {
  constructor (client) {
    super(client)
    this.url = '/v2/worldbosses'
    this.isPaginated = true
    this.isBulk = true
    this.isLocalized = true
    this.cacheTime = 24 * 60 * 60
  }
}

// ... code ...

Should be easily transformed into something like this:

- [`api().worldbosses()`](#apiworldbosses) - Information about the available world bosses.

<!-- Further down -->

### `api().worldbosses()`

> Information about the available world bosses.

- **API-URL:** [/v2/worldbosses](https://api.guildwars2.com/v2/worldbosses)
- **Paginated:** Yes
- **Bulk expanding:** Yes
- **Authenticated:** No
- **Localized:** Yes
- **Cache time:** 24 hours

<sup>[↑ Back to the overview](#available-endpoints)</sup>

---

Update the client to the new endpoints

  • /v2/account/mailcarriers
  • /v2/account/pvp/heroes
  • /v2/account/mastery/points
  • /v2/pvp/heroes
  • /v2/commerce/delivery
  • /v2/guild/:id/storage
  • /v2/cats
  • /v2/mailcarriers
  • /v2/nodes

indexdb caching sometimes returns wrong values

Hi, I noticed that sometimes I get wrong values from the cache when I query stuff back to back.
This might be because I am using #72 already.

this.item = await this.api.gw2api.items().get(this.itemId);
console.log(`Itemid: ${this.itemId}`, this.item);
const tpval = await this.api.gw2api.commerce().prices().get(this.itemId);

Sometimes if this gets called a 2nd time the log output will be of the commerce api return not the item.

I haven't looked deeper into it yet, just wanted to let you know. I believe that it is a bug in the autoBatch function.

An in-range update of abc-environment is breaking the build 🚨

The devDependency abc-environment was updated from 2.0.2 to 2.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

abc-environment is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 32 commits.

  • 0379a99 2.0.3
  • 20b69af Update README.md
  • 3e4dbb4 Update README.md
  • cb98c87 Merge pull request #61 from queicherius/greenkeeper/standard-11.0.0
  • 93c0021 Merge pull request #59 from queicherius/greenkeeper/chalk-2.2.0
  • 6ec56d0 Merge pull request #58 from queicherius/greenkeeper/mocha-4.0.0
  • 3af3b01 Merge pull request #57 from queicherius/greenkeeper/sinon-4.0.0
  • 05ee1c8 Merge pull request #56 from queicherius/greenkeeper/babel-eslint-8.0.0
  • ccf970b Merge pull request #55 from queicherius/greenkeeper/exec-sh-0.2.1
  • d359675 fix(package): update standard to version 11.0.0
  • 0ef3394 fix(package): update chalk to version 2.2.0
  • 9d3b0a0 fix(package): update mocha to version 4.0.0
  • 9dfdad8 fix(package): update sinon to version 4.0.0
  • ffbbcc4 fix(package): update babel-eslint to version 8.0.0
  • e10646e fix(package): update exec-sh to version 0.2.1

There are 32 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of rusha is breaking the build 🚨

Version 0.8.10 of rusha was just published.

Branch Build failing 🚨
Dependency rusha
Current Version 0.8.9
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

rusha is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 3 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Add simple caching behaviour

Since writing all the bulk ids can be super straining and we usually request the same ids over and over again, just write the requests itself into the cache?

Add the new API endpoints

  • /v2/pvp/ranks
  • /v2/pvp/seasons/:id/leaderboards/:board/:region
  • /v2/wvw/matches/overview
  • /v2/wvw/matches/scores
  • /v2/wvw/matches/stats
  • /v2/wvw/ranks (via #13)

An in-range update of debug is breaking the build 🚨

Version 3.2.2 of debug was just published.

Branch Build failing 🚨
Dependency debug
Current Version 3.2.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

debug is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 1 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Write a propper cache interface for the browser

Requirements

  • Quick write and read performance
  • Able to write and read a lot of different keys quickly (e.g. via batch operations)
  • Persistent storage - stays alive after browser restarts
  • Storage limit high enough so the cache actually makes sense (50mb?)
  • Asynchronous and non-blocking

Tested

  • localStorage: Fast reads/writes (< 1ms per item), but no batch operations, low storage limit and blocking
  • levelup: Slow as hell (100ms - 1500ms per item read/write performance)
  • localForage: Slow as hell (1500ms+ per item read/write performance)
  • pouchdb: Still too slow (13s for writing 50k documents, 1.5s for reading 50k documents)

An in-range update of promise-control-flow is breaking the build 🚨

The dependency promise-control-flow was updated from 1.2.4 to 1.2.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

promise-control-flow is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 4 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

PvP Leaderboards

With the current implementation its not possible to get the leaderboards of the old pvp seasons, beacause the leaderboard was not called ladder, but legendary and guild (ref).

The name of future leaderboards might change again, so its probably a good idea to not hardcode the leaderboard name.

Edit: And another thing I just noticed, you haven't marked the leaderboard endpoint as paginated, but it is (example: requesting rank 200 (?page=199&page_size=1)).

Add better mocking capabilities

Let's face it, mocking with the underlying request library is not fun. It's also not fun replacing this library with code like the following.

// Current ugly unit test
myModule.__set__('api', () => ({
  language: () => ({
    finishers: () => ({all: () => finisherData})
  }),
  finishers: () => ({all: () => finisherData})
}))

Instead, this module should offer a better way to handle mocking in unit tests that depend on this module.

Rewrite without ES2015 classes

I would like to see if rewriting the library to be fully functional based and removing es2015 removes a lot of the overhead. Currently still evaluating.

An in-range update of url-parse is breaking the build 🚨

Version 1.1.9 of url-parse just got published.

Branch Build failing 🚨
Dependency url-parse
Current Version 1.1.8
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

url-parse is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪

Status Details - ✅ **continuous-integration/travis-ci/push** The Travis CI build passed [Details](https://travis-ci.org/queicherius/gw2api-client/builds/228420028?utm_source=github_status&utm_medium=notification),- ❌ **codecov/project** 99.9% (-0.1%) compared to 9b90ec0 [Details](https://codecov.io/gh/queicherius/gw2api-client/commit/708d0737a2a876b6ded3b68d4b5238cc00e0d24f),- ✅ **codecov/patch** Coverage not affected when comparing 9b90ec0...708d073 [Details](https://codecov.io/gh/queicherius/gw2api-client/commit/708d0737a2a876b6ded3b68d4b5238cc00e0d24f)

Commits

The new version differs by 9 commits0.

  • 86d3d6d [dist] 1.1.9
  • 8865be4 Merge pull request #60 from unshiftio/gh-49
  • e06eb7f [minor] Merge lolcation into main module
  • e9373aa [codestyle] Remove spurious semicolon
  • ab5b277 chore(package): update mocha to version 3.3.0 (#59)
  • b38ed7a chore(package): update browserify to version 14.3.0 (#58)
  • f096cf2 Merge pull request #56 from unshiftio/greenkeeper/assume-1.5.0
  • f306333 chore(package): update assume to version 1.5.0
  • e2358c1 fix(package): update querystringify to version 1.0.0 (#55)

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Add new endpoints 2017-03-01

  • /v2/races
  • /v2/dungeons
  • /v2/account/dungeons
  • /v2/raids
  • /v2/account/raids
  • /v2/account/home/nodes
  • /v2/account/home/cats
  • /v2/wvw/upgrades

Update with new endpoints

  • /v2/createsubtoken
  • /v2/account/mastery/points
  • /v2/quests & /v2/characters/:id/quests
  • /v2/emotes & /v2/account/emotes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.