Giter Site home page Giter Site logo

brandoncookedev / smashgg.js Goto Github PK

View Code? Open in Web Editor NEW
33.0 9.0 12.0 2.17 MB

Node.JS SDK for the Smash.gg public API.

Home Page: https://www.npmjs.com/package/smashgg.js

JavaScript 3.60% TypeScript 96.30% Shell 0.10%
smashgg tournament brackets gg-api smash-bros fgc sdk nodejs

smashgg.js's Introduction

smash.gg logo smashgg.js

node version package version downloads last commit minizipp size repo size license

Node.js SDK for the public Smash.gg API, which is rich with data about tournament brackets that have occurred on their platform.

require('colors');
const smashgg = require('smashgg.js');
const {Event} = smashgg;

smashgg.initialize('<your api key>');

(async function(){
    let tournamentSlug = 'function-1-recursion-regional';
    let eventSlug = 'melee-singles';
    let meleeAtFunction = await Event.get(tournamentSlug, eventSlug);

    let sets = await meleeAtFunction.getSets();
    let phaseGroups = await meleeAtFunction.getPhaseGroups();

    console.log('Function 1 had %s sets played in %s phase groups', 
        sets.length, phaseGroups.length);

    console.log('Set Results:')
    for(var i in sets){
        console.log(`${String(sets[i].getFullRoundText()).magenta}: ${String(sets[i].getDisplayScore()).green}`);
    }

    return true; // exit async
})()

Results: example

Author: Brandon Cooke

Installation

npm install --save smashgg.js

Issues

Contents


Getting Started

To begin coding with the SDK, you need an Access Token. You may get one by Joining the Smash.gg discord and asking Furtive for an API key.

Once you have this key, you may use the following function to authenticate with the API and then you may move on

// import the SDK
const smashgg = require('smashgg.js');

// authenticate with key
smashgg.initialize('<your api key here>');

Limitations

Currently, smashgg.js is limited by Smash.gg's rate limiting rules. Those are currently 80 requests per 60 seconds. That is, every request made to the API starts a 60 second timer. If 80 requests are made before the first 60 second timer is completed, your next request will be dropped.

This SDK implements a Queueing system when your code becomes "Delinquent", that is it has made too many requests too fast. Your requests won't be dropped, but rather will wait until the next available request slot opens.

If you wish to see this queuing info, it is recommended you maintain the "info" logging level (See Logging).


Access to V1-V3

The original API has no Sunset date set currently. While this is the case, I thought it best to make the original SDK available to people so that they may maintain their apps while beginning to move into V4. You may access v1-v3 SDK as follows:

let smashggV1 = require('smashgg.js/src/v1');

Logging

Winston

You can access the built in Winston logger by using the following methods

const smashgg = require('smashgg.js');
let log = smashgg.Log;

log.info('Here\'s some text')
log.debug('Don\'t print this here')

smashgg.setLogLevel('debug')
log.info('Print everything now!!')
log.verbose('Not to be verbose...')
log.debug('but i\'m trying to debug :)')

smashgg.setLogLevel('warn');

You can also add a Logger of your own, say if you'd like a File logger added

const smashgg = require('smashgg.js')
let log = smashgg.Log

smashgg.addLog('file', {
    filename: '/tmp/log',
    level: 'verbose',
    format: winston.format.combin(
        winston.format.splat(),
        winston.format.simple()
    )
})

The following are the operations at your disposal

  • setLogLevel(level)

    • level: string
      • Valid values are
        • error
        • warn
        • info
        • verbose
        • debug
  • addLog(type, options)

    • type: string
      • valid values:
        • console
        • file
    • options: winston.LoggerOptions
  • disableLog()

    • disabled the embedded logger
  • enableLog()

    • enables the embedded logger

Upgrading

This section is for detailing the transition between major versions.

V3 to V4

Easily the largest change that has occurred in the lifespan of this SDK. Please read carefully to successfully upgrade versions.

  • All major objects (Tournament, Event, Phase, PhaseGroup) have refactored the main getter renamed to get()
    • Tournament.getTournament(slug) ==> Tournament.get(slug)
    • Event.getEvent(eventName, tournamentName) ==> Event.get(tournamentName, eventName)
    • Phase.getPhase(id) ==> Phase.get(id)
    • PhaseGroup.getPhaseGroup(id) ==> PhaseGroup.get(id)
  • Event no longer accepts Tournament slug shorthand
    • shorthand like "function1" need to be refactored to their full slug version like "function-1-recursion-regional"
  • Tournament no longer has aggregate functions like getAllSets() or getAllPlayers()
    • due to the limitations, the SDK can no longer support aggregate functions for Tournament objects, I recommend using individual Event objects to accomplish your goals
  • Take caution in doing aggregate functions on Events of very large size, like Evo Melee or something similar. You could find yourself hitting the rate limit very easily.

Maintaining V1-V3

As described in Access V1-V3, you may use the original SDK while it has not been Sunset. See that section for more details.

V2 to V3

In order to transition successfully from V2 to V3, please ensure the following All Set objects created by smashgg.js are renamed to GGSet

V1 to V2

In order to transition successfully from V1 to V2, please ensure the following

  • Event constructors now take eventId parameter before tournamentId parameter.
    • Additionally, you can give the constructor an Id number for the event, and null tournamentId.
  • Tournament, Event, Phase, and PhaseGroup constructors now take an options object that encapsulates the previous isCached and expands parameters.
    • Please see documentation for further implementation.
  • It is suggested you move to the Promise returning convenience methods, as the previous ready event will be deprecated from this point on.
    • Please see documentation for the convenience methods. They take the same parameters as the constructor.

smashgg.js's People

Contributors

actions-user avatar bartdebever avatar brandoncookedev avatar dependabot[bot] avatar eiabea avatar golee5191 avatar jarrodblanton avatar joshmontech avatar resicapdevops 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

smashgg.js's Issues

Implement Concurrency control on bulk pull functions

Currently Bulk Pull functions like Tournament.getAllPlayers() or Event.getSets() end up running all data fetching promises at once concurrently.

This ticket is to implement concurrency control, probably using p-map, to allow users to specify amount of pull they want at once for a variety of reasons (network capability, potential smashgg throttle)

CORs error from smashgg

Hi, I am getting a CORs error from smash.gg itself. Do I need to add headers to the request to make it work? I tried 'mode':'no-cors'. Currently I am testing from localhost. Any help would be appreciated, thanks!

image

Add network logging when pulling objects

Sometimes, it's tough being a dev.
It's really tough when you don't know if a function call is still working.

If possible, should implement some sort of optional logging telling a user that an operation is still running and is just taking a while (because v1 of smashgg's api can be slow at aggregating data)

Get Sets for Phase

Getting all the sets for a Tournament object is nice, but sometimes a user doesn't want all that data, and shouldn't have to further filter through it.

We should give the user an Phase.getSets() function to allow additional filtering up front.

Some slugs break getTournament

Specific example is The Big House 7 slugs have some issue that needs to be caught and handled.
Slugs: tbh7, the-big-house-7

Optionally Disable Logger

Let users disable the default smashgg logger if they so desire.
Additionally, add another function to turn it back on. This was discussing in #34

Add express object creation functions

using the code in the following fashion can be quite cumbersome

let t = new Tournament(TOURNAMENT_NAME);
t.on('ready', function(){
    //t is now populated and accessible
})

We can offer static functions that perform this operation for them and returns a promise resolving the object value

function getTournament(tournamentName){
    return new Promise(function(resolve, reject){
        let t = new smashgg.Tournament(tournamentName);
        t.on('ready', function(data){
            resolve(t);
        });
    })
}

We should implement this for convenience.

Pagination issue for getSets()

trying to get every set from a ladder event and total matches and some of the sets were incorrect. I could only see half of the sets that I played and those few sets were repeated through out the getSets() result.

possible there is a bug in the paginated sets causing it to double count the initial pull

the tourney slug I used for testing was 'smash-and-ladders' and event was 'melee-singles'

Split Event by Id and Tournament/Event Name into Inherited classes

Currently the Event object takes situational parameters and then deterministically pulls Event data (ie event id is optional or tournament name is optional if id exists).

However, these should be more cut and dry. We should have two new Objects that extend to Event

  • EventById
  • EventByNames

Both of these will extend to the Event superclass and share the same general logic/getters.

Require Module Error

I was trying to use this lib for my project with smashgg API.
I recently had to reinstall the entire project inclusing this lib.
But with the last update I have an strange error :
`PS C:\**\GitHub\smashgg-attendees-counter> node .\index.js
internal/modules/cjs/loader.js:716
throw err;
^

Error: Cannot find module './src/v4/js'
Require stack:

  • C:\**\GitHub\smashgg-attendees-counter\node_modules\smashgg.js\index.js
  • C:\*\GitHub\smashgg-attendees-counter\index.js
    �[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:713:15)�[39m
    �[90m at Function.Module._load (internal/modules/cjs/loader.js:618:27)�[39m
    �[90m at Module.require (internal/modules/cjs/loader.js:771:19)�[39m
    �[90m at require (internal/modules/cjs/helpers.js:68:18)�[39m
    at Object. (C:\
    *\GitHub\smashgg-attendees-counter\node_modules\�[4msmashgg.js�[24m\index.js:1:18)
    �[90m at Module._compile (internal/modules/cjs/loader.js:868:30)�[39m
    �[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:879:10)�[39m
    �[90m at Module.load (internal/modules/cjs/loader.js:731:32)�[39m
    �[90m at Function.Module._load (internal/modules/cjs/loader.js:644:12)�[39m
    �[90m at Module.require (internal/modules/cjs/loader.js:771:19)�[39m {
    code: �[32m'MODULE_NOT_FOUND'�[39m,
    requireStack: [
    �[32m'C:\**\GitHub\smashgg-attendees-counter\node_modules\smashgg.js\index.js'�[39m,
    �[32m'C:\**\GitHub\smashgg-attendees-counter\index.js'�[39m
    ]
    }`

For me it means that /src/v4/js doesn't exist and in fact I can't find it in the node_module folder:
image

What can I do to solve this problem ? Thks

Winston issues:

Ever since upgrading winston to v3 this has been happening:

image

Need to rethink and re-implement logging functionality.

Create Version 4, Implementing new GQL API

As Smashgg updates their API, should refactor to use their GQL offerings.

Version 4 - Refactor how data is retrieved and how it is stored in smashgg.js.
Version 5 - Refactor a lot about how objects are created and returned.

Make Set more Robust

Currently, the Set object is coupled to a set being complete (ie the winnerId and loserId properties being populated)

However, not all sets will be complete, and some may with to get in-progress Sets.

This ticket is to expand the logic of the Set object to be more generalized for both complete and non-complete situations.

I can't install.

My problem is simple, I can't install this package. Every time I tried it, it outputs the same stuff:

npm ERR! Unexpected end of JSON input while parsing near '....10","moment":"^2.22.'
npm ERR! A complete log of this run can be found in:
npm ERR!     %APPDATA%\npm-cache\_logs\2018-11-16T07_55_58_306Z-debug.log

It only happens to this package, any other package installs just fine.

Winston Logging Issue: No Stack Trace Printing

Hi, I'm having an issue with the Winston logging.
Once I call smashgg.initialize(), all errors are printing without a stack trace, and nothing I do (whether trying to change logs through the smashgg.js-provided functions or through adding transports to the global Winston object) seems to have any effect whatsoever.
Info logs are printing normally.
This has hijacked error logging throughout my application, making it almost impossible to debug without any stack traces. I've tried lots of solutions, but the second I call smashgg.initialize() everything switches over to the broken version.
I've boiled it down to the simplest possible app, and still the issue persists.

Expected behavior:

Error logs that look like this:

s()
^

ReferenceError: s is not defined
    at Object.<anonymous> (/Users/jasper/github/positivity2/index.js:14:1)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
    at internal/main/run_main_module.js:17:11

Actual behavior:

Error logs that look like this:

s is not defined
NOTE: Check your debug log for stack trace
[winston] Attempt to write logs with no transports {"level":"debug"}

Node v12.6.0

index.js

require('dotenv').config()
const smashgg = require('smashgg.js')
const winston = require('winston')
smashgg.disableLog() // has no effect
smashgg.addLog('console', { // also has no effect
  level: 'debug',
  transports: [new winston.transports.Console()],
}) 

// if the initialize line below is commented out, the stack trace prints correctly.
// if not, it prints:
//   s is not defined
//   NOTE: Check your debug log for stack trace
//   [winston] Attempt to write logs with no transports {"level":"debug"}"
smashgg.initialize(process.env.SMASHGG_APIKEY)

s()

package.json

...
"dependencies": {
    "dotenv": "^8.2.0",
    "smashgg.js": "^4.1.10",
    "winston": "^3.2.1" 
  },
...

^ I updated winston to ^3.2.1 just to see if it fixed the issue. The behavior is the same with a fresh install of smashgg.js with no manual Winston updates.

Functions to get Common set groups

It seems to be a typical scenario for someone getting data real-time during a tournament to want the typical sets that happen in an event. Things like

  • Top 8
  • Top 32
    etc

We should have functions in the Tournament and Event objects to resolve those from the data.

Expands Logic is Broken

The current logic reads

this.expands = {
            event: (expands && expands.event) || true,
            phase: (expands && expands.phase) || true,
            groups: (expands && expands.groups) || true,
            stations: (expands && expands.stations) || true
};

This is incorrect and will always resolve true, because even if expands exists and expands[property] exists AND expands[property] is false, the entire first conditional resolves false which triggers the OR and assigns true.

The following should fix the logic, and should be applied to Tournament, Event, Phase, and PhaseGroup

this.expands = {
            event: (expands && expands.event == false) ? false : true,
            phase: (expands && expands.phase == false) ? false : true,
            groups: (expands && expands.groups == false) ? false : true,
            stations: (expands && expands.stations == false) ? false : true
};

Cannot query errors for Tournament

When trying to get a tournament using Tournament.get(); I keep getting multiple query errors:
image
(The slug in my example is a tournament that was supposed to be hosted in April)
I think this might be an issue with Tournament in the schema/GraphQL.

getAllSets() of some tournaments causes memory problems

When i try to get all GGSets of certain tournaments i get a Javascript heap of of memeory error.

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

One of those tournaments is https://smash.gg/tournament/net-battle-series-5/events/ultimate-singles/brackets/512334/879036.

I dont think this actually is a memory problem, in a way that there are too many GGSets loaded into memory because i can load GGSets from much bigger tournaments with no problem.

If it helps, my code looks like this:

for (var n = 0; n < slugs.length; n++) {
        let tournament = await Tournament.getTournament(slugs[n]);
        let sets = await tournament.getCompleteSets();
        console.log(sets.length);
    }

Rename data property as raw, and base64 it.

Currently, all the raw data for an object that comes from smash.gg is stored in Smash.gg Object's data property (Tournament.data, Event.data, etc).

Firstly, this property should just be called raw for naming convention.

Secondly, this additional storage is great for a user to get anything they desire from the data in one fell swoop. However, it can be kind of cumbersome on memory to store these massive objects on the stack.

To solve this, we can stringify and base64 this data. And if the user ever wants the data back in JSON, they may call a getRaw() function which reverses the encoding and returns a JSON parse of the string.

Characters.getByGameName doesnt work on latest version

I tried to fetch the characters from 'super-smash-bros-ultimate'
But i constantly get error messages. It doesnt work with version '^3.0.2' but works with '2.3.8'

The code looks like this:

var smashgg = require('smashgg.js');
var { Character} = smashgg;

let meleeCharacters = Character.getByGameName('super-smash-bros-ultimate').then((e) => {
    console.log(e);
});

Error:

(node:12524) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getByGameName' of undefined ...
(node:12524) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)(node:12524) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Get Sets for Individual Events

Getting all the sets for a Tournament object is nice, but sometimes a user doesn't want all that data, and shouldn't have to further filter through it.

We should give the user an Event.getSets() function to allow additional filtering up front.

accessing the logger doesnt work

I want to disable the winston logger but cant seem to access it in the way it is explained in the docs.
Seems like:

var smashgg = require('smashgg.js');
smashgg.setLogLevel('warn');

doesnt work, it keeps throwing undfinded error for setLogLevel().

What format are timestamps in?

Timestamps seem to be in another format than ms since Jan 1, 1970. For example, I get timestamps like 1579137495 for matches in an event that took place last year, but when I check it (using new Date(1579137495) or on a website like https://currentmillis.com/), it appears to be a date in 1970. What format are dates being recorded in?
Thanks!

Leading Digit Tournament Names Parsed as ID

Currently, Tournament.js will parse a tournament name that has leading digits taking the digits and interpreting them as an ID number.

Ex:
Tournament: "21xx-cameron-s-birthday-bash-1"
Tournament.js parses 21 as tournament id and fails.

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.