twitchio v1.1.0
TwitchIO
A redesign of twitch-js-sdk using modern JavaScript, this modules provides an IO medium for the Twitch API.
This module is written in ES6, and currently requires a suitable module loader to get you off the ground.
Install
This module is intended for use in the browser.
Suggested installation via jspm
.
jspm install npm:twitchio
whatwg-fetch
and bluebird
are pulled in as polyfills for fetch
and Promise
, respectively.
The sessionStorage
API is assumed to be otherwise implemented.
Breakdown
This module has a single export, the TwitchIO
class. In turn, the class constructor takes a single argument, a String
value representation of your Twitch API client ID.
import TwitchIO from 'twitchio';
let TwitchClient = new TwitchIO('MY_API_KEY');
For the rest of this document, TwitchClient
will refer to an arbitrary instance of TwitchIO
.
TwitchIO
instances are a type of event emitter, so read the Events section for information regarding that topic.
Properties
TwitchIO
instances have two unique properties.
key :: String
The application client ID.
session :: Session
A representation of the current user session. Read ahead for more information about Session
objects, and how TwitchIO
instances receive them.
Prototype Methods
TwitchIO
instances have access to three direct prototype methods.
request
Promise <- request (base :: Object, options :: Object)
The request
method is used to issue lowish level requests to Twitch API endpoints, and can be used to abstract higher level methods for repetitive tasks. It emits a 'request'
event just before making the actual request.
base
is an object used to specify API endpoints, and query strings. It cares about the following properties, each being optional.
endpoint :: String
The target API endpoint. Defaults to an empty string, resulting in the root API URI.
query :: Object
A mapping of query string keys and values.
application :: Boolean
Makes request on behalf of the application, adding the instance's key
to the query string.
Should be used in all serious calls to the API, to avoid excessive rate limiting.
user :: Boolean
Makes request on behalf of the user, adding the token
, if one exists, from the instance's Session
to the query string.
There is no feedback if a
token
does not exist. In that event, this property is silently ignored.
options
is an initializer object for a fetch
invocation. This is where you would define an HTTP method
, among other things. It is optional.
The return value is a Promise
, which resolves when the request completes, and the response body has been parsed. Since all requests return valid JSON, the Promise
chain rejects when the response data contains an error
property - rejecting with an entire TwitchError
object.
Examples
Getting top games, with query string parameters.
TwitchClient.request({ endpoint: 'games/top', query: { limit: 25 } })
.then(data => console.log(data));
// Object {_total: 999, _links: Object, top: Array[25]}
Catching an error object.
TwitchClient.request({ endpoint: 'fake/endpoint' })
.catch(error => console.log(error));
// TwitchError {error: "Not Found", status: 404, message: null}
connect
void <- connect (options :: Object)
The connect
method is used to ask Twitch users to approve a connection with your application, giving it certain read or write permissions, and granting the user an OAuth token. It takes a single argument - an options
object. It returns nothing, because it will immediately redirect the page. It does, however, emit a 'connect'
event just before redirection takes place.
The options
object is required, as are two of its four expected properties:
redirect :: String
(required)
This is the redirect URI, or the returning entry point to your application. It should match the value provided when your application was registered with the API.
scope :: Array<String>
(required)
This must be an array of scopes your application is requesting access to. Pass an empty array if you require no scopes.
force :: Boolean
(optional)
Whether the connection attempt should force the user to reauthorize the application.
state :: String
(optional)
An OAuth state token to be exchanged with the authorization server.
Example
Invoking connect
with our required arguments.
TwitchClient.connect({
redirect: 'https://my.redirect',
scope: ['user_read', 'channel_read']
});
disconnect
void <- disconnect ()
The disconnect
method simply destroys any JSON-form Session
object stored in the sessionStorage
, and creates a new, empty Session
object on the instance. This does not invalidate any OAuth tokens, or log the user out of Twitch. Emits a 'disconnect'
event.
Example
Invoking disconnect
.
TwitchClient.disconnect();
Events
TwitchIO
uses a dead simple event emitting implementation, internally called Eventful
. As such, instances have access to a few more properties and methods.
Properties
events :: Object
This is a key store of event names, and their associated lists of handlers. Try not to mess with it directly.
Prototype Methods
on
this <- on (event :: String, block :: Function)
The on
method adds the given block
to the list of functions associated with the given event
.
off
this <- off (event :: String, block :: Function)
The off
method removes all references to the given block
from the list of functions associated with the given event
. Important: If no block
is specified, all functions are removed from the list.
emit
this <- emit (event :: String, ...args)
The emit
method invokes any and all functions stored in the list associated with the given event
, passing all remaining args
as the arguments to each function, with the contextual this
as the invoking instance.
Sessions
Session
objects are representations of current user sessions. TwitchIO
instances always have a Session
object stored in their session
property, unless externally tampered with.
The session
property may change over the lifetime of a TwitchIO
instance, so holding long-term, direct references to the session object is ill advised.
Whether these objects contains useful data is entirely reliant on the flow of your application.
Creation
A Session
object is created for TwitchIO
instances during their construction. These Session
objects are initially created in one of four ways.
A predictable, and expected
location.hash
string.The location's
hash
is first tested to see if aSession
can be created from the values present. This is important to note: following OAuth's Implicit Grant Flow, this is the only way to parse a returning request for a session. As such,TwitchIO
instances should be constructed before any other sources possibly tamper with thehash
string (e.g., page routing solutions).A predictable, and expected
location.search
string.A second test is run against the location's current
search
value. If a user denies your application authorization, the return data is sent in the query string, not the hash. Again,TwitchIO
instances should be constructed before any other sources tamper with thesearch
string.Loaded from the
sessionStorage
.If neither the
hash
orsearch
strings hold expected values, creation of aSession
object is attempted by way of parsing whatever data is currently held in the expected key store of thesessionStorage
.Empty construction.
If none of the above steps yield data, a brand new
Session
object is created, full ofnull
values.
Notes:
- If steps 1 or 2 are successful, the new
Session
object is stored in thesessionStorage
. - When
disconnect
is called, a new, emptySession
object is created for the invoking instance.
Properties
Every Session
object has five unique properties. Any given property will contain null
, if in a default, empty state.
token :: String
The user's OAuth token. Evidence of what is very likely to be a usable session.
scope :: Array
An array containing the authorized scopes.
state :: String
An OAuth state token.
error :: String
Evidence of a session error, in the form of a simple error message.
status :: String
General information, usually an expanded error message.
License
Enjoy!
Colin 'Oka' Hall-Coates