npm package: @mediaplatform/sportal365-football-sdk-node
Description: ### Installation
Author: smp@sportal.bg
Latest version: 1.0.13

# JavaScript Football SDK

### Installation

Install Football SDK dependency

```sh
npm install @mediaplatform/sportal365-football-sdk --save
```

or

```sh
yarn add @mediaplatform/sportal365-football-sdk
```

### Usage

Import Football SDK dependency

```sh
import Core from "@mediaplatform/sportal365-football-sdk"
```

Initialize Football SDK

```sh
const SDK = new Core(config);
```

The **config** argument is an object with the following properties:

- **baseUrl** - API URL
- **apiKey** - API KEY
- **lang** - example: 'en'
- **oddClient** - example: 'sportal'
- **assets?** - The property is optional and if it is not provided all data with missing logos from the API will have default placeholders.

  The **assets** object could have **some** or **all** of the following properties with values coresponding to desired placeholders (base64
  image or valid url) to display:

  ```sh
  {
      player: '',
      lineup_player_type: '',
      coach: '',
      referee: '',
      president: '',
      team: '',
      imagePlaceholder: '',
      blankPlaceholder: '',
      tournament: '',
      stage: '',
      flag: '', // use this property for country flag placeholder
      venue: '',
      city: '',
      match_status: '',
      club: '',
    provider: ''
  };
  ```

## Player Module

Initialize module

```sh
const playerModule = SDK.player(playerId);
```

**playerId** - the argument is required (playerId: string). It defines the required player.

### Usage 1

```sh
playerModule.get();
```

Corresponding output should be:

```sh
{
  player: PlayerModel
};
```

### Usage 2

```sh
playerModule.withCareer(type).get();
```

Corresponding output should be:

```sh
{
  player: PlayerModel,
  statistics: [PlayerStatisticsModel],
};
```

### Usage 3

```sh
playerModule.withSeasonStatistics(seasons).get();
```

Corresponding output should be:

```sh
{
  player: PlayerModel,
  statistics: [PlayerStatisticsModel],
};
```

### Usage 4

```sh
playerModule.withCurrentLeagueStatistics().get();
```

Corresponding output should be:

```sh
{
  player: PlayerModel,
  statistics: [PlayerStatisticsModel],
};
```

##### NOTE: You should invoke only one of the following methods at the same instance: withCareer(), withSeasonStatistics() and withCurrentLeagueStatistics(). If you chain them, only the first one called will be executed.

Module methods:

- **withCareer(type?: string)** - Use this method to filter player statistics by specific type.
  - type - the argument is optional and could be one of the following string values: 'national', 'international' or 'regional'. If you do
    not pass an argument, all statistics will be showed.
  ```sh
  { statistics: [PlayerStatisticsModel] };
  ```
- **withSeasonStatistics(seasons?: string[])** - Use this method to filter player statistics by seasons.
  - seasons - The seasonIds argument is optional and should be an array of all desired season Ids to filter standing groups result.

```sh
 { statistics: [PlayerStatisticsModel] };
```

- **withCurrentLeagueStatistics()** - Use this method to get player statistics for the current league.

```sh
{statistics: [PlayerStatisticsModel]};
```

- **get()** - the method is mandatory - Based on called methods, it returns the built object with player statistics for specific type,
  seasons or current league.

## Match Module

Initialize module

```sh
const matchModule = SDK.match(eventId);
```

**eventId** - the argument is required (eventId: string). It defines the required match event.

### Usage

```sh
matchModule
  .withCommentary()
  .withStats()
  .withLineups()
  .withMatchEvents(options)
  .withOdds()
  .withStanding(options)
  .get();
```

Corresponding output should be:

```sh
{
  match: MatchModel,
  commentary: data,
  stats: TeamStatisticsModel,
  lineups: LineupModel,
  matchEvents: MatchEventGroupedModel,
  odds: { eventId: '', odds: OddsModel},
  markets: { markets: marketOptions },
  standing: StandingObjectModel
  rules: [RulesModel]
};
```

Module methods:

- **withCommentary()**

```sh
{ commentary: data };
```

- **withStats()**

```sh
{ stats: TeamStatisticsModel };
```

- **withLineups()**

```sh
{ lineups: LineupModel };
```

- **withMatchEvents(options?)**

  - options - the argument is optional. It should be an object with one or 2 parameters: Example: {group_by: 'team', direction: 'asc'} The
    direction property could be with 'asc' or 'desc' value. Any other key-value pairs will be ommited.

Without options the output is:

```sh
{ matchEvents: MatchEventModel };
```

With options, the output is:

```sh
{ matchEvents: MatchEventGroupedModel };
```

- **withOdds(options: {providersIds: number[]})**
  - options - the argument is an object where providersIds property should be an array of providers Ids (numbers) to filter odds result.
    Example: [43] - will return available odds data (if there is one) only for odds with the given provider. Example: [] - will return all
    available odds without filtration by providerIds

```sh
{
  odds: OddsModel,
  markets: marketOptions
}
```

- **withStanding(options: { expand: string, groups: number[], teamOffset: { teamId: number; offset: number }})**

##### Stage id used to get standing will be taken from the match stage.

**The options argument is an object with the following properties:**

- expand - You must specify the required expand and it could be one of the following values: **'RULES'**, **'FORM'**, **'RULES_FORM'**,
  **'RULES_FORM_EVENTS'** or **'FORM_EVENTS'**. The default value is **'RULES_FORM'**,
- groups - You could pass an array of group id`s to filter standing groups.
- teamOffset - an object with teamId and an offset number to slice standing result with.

```sh
{ teamId: number; offset: number }
```

- **get()** - the method is mandatory - Based on called methods, it returns the built object with all requested information for the match
  event, teams, stage standing and odds.

## Standing Module

Initialize module

```sh
const standingModule = SDK.standing(stageId);
```

**stageId** - the argument is required (stageId: string). It defines the standing stage.

### Usage

```sh
standingModule.withStandingConfig(expand).withGroups([1, 2, 3...]).withTeamOffset(teamOffset).withRules().get();
```

If the stage has standing the output should be:

```sh
{ standing: StandingObjectModel, rules: [RulesModel] };
```

Module methods:

- **withStandingConfig(expand: string)**
  - expand - the argument could be one of the following string values: **'RULES'**, **'FORM'**, **'RULES_FORM'**, **'RULES_FORM_EVENTS'** or
    **'FORM_EVENTS'**. If You do not pass the **expand** argument will be used the default value - **'RULES_FORM'**,

The method Output is:

```sh
{ standing: StandingObjectModel };
```

- **withTeamOffset(teamOffset: { teamId: number; offset: number })** - Use this method to filter standing by specific team and offset.
  - teamOffset - an object with teamId and an offset number to slice standing result with.
  ```sh
  { teamId: number; offset: number }
  ```
- **withGroups(groups: number[])** - Use this method to filter standing groups.
  - groups - The groups argument should be an array of all desired groups Ids to filter standing groups result. The following example will
    return available standing data (if there is one) only for groups with these ids.

```sh
const groups = [921, 922, 933];
```

- **withRules()** - Use this method to include extracted data of all existing rules in standing.

```sh
{ rules: [RulesModel] };
```

- **get()** - the method is mandatory - Based on called methods, it returns the built object with standing rules and filtered standing
  information for the given stage and expand.

## Odds Module

Initialize module

```sh
const oddsModule = SDK.odds(eventId);
```

**eventId** - the argument is required (eventId: string). It defines the required match event odds.

### Usage

```sh
oddsModule
  .filterOddsByProvidersIds(providersIds)
  .withMarkets()
  .get();
```

If the event has odds the output should be:

```sh
 { odds: { eventId: '', odds: OddsModel} };
```

Module methods:

- **withMarkets()** - The method returns all existing markets in odds

marketOptions = [ { key: '1x2', label: '1x2' }, { key: 'overUnder', label: 'Over/Under' }, { key: 'doubleChance', label: 'Double chance' },
{ key: 'bothScore', label: 'Both score' }];

The method Output is:

```sh
{ markets: marketOptions };
```

- **filterOddsByProvidersIds(providersIds: number[])**
  - providersIds - the argument should be an array of providers Ids (numbers) to filter odds result. Example: [43] - will return available
    odds data (if there is one) only for odds with the given provider. Example: [] - will return all available odds without filtration by
    providerIds

The method Output is:

```sh
{ odds: OddsModel };
```

- **get()** - the method is mandatory - Based on called methods, it returns the built object with all requested information for the odds,
  extracted markets and filtered odds by the given providers ids.

## Decorated Players module

Initialize module

```sh
const decoratedPlayersModule = SDK.decoratedPlayersForSeason(seasonId);
```

**seasonId** - the argument is required (seasonId: string). It defines the required season.

### Usage

```sh
decoratedPlayersModule
  .filterDecoratedPlayers(options)
  .withPlayerOffset(options)
  .withStartFromPosition(position)
  .limitPlayers(number)
  .get();
```

If the season has players the output should be:

```sh
{ decoratedPlayersForSeason: DecoratedPlayersModel };
```

- **filterDecoratedPlayers()**

#### Usage 1 - filterDecoratedPlayers({ teamId: number })

- teamId - an object with teamId(number) to filter players. Example: 110 - will return available players data (if there is one) only for
  players with the given team.

#### Usage 2 - filterDecoratedPlayers({ playerId: number })

- playerId - an object with playerId(number) to filter players. Example: 110 - will return available players data (if there is one) only for
  players with the given id.

#### Usage 3 - filterDecoratedPlayers({ card: string })

- card - an object with card color (yellor or red) to filter players. Example: red - will return available players data (if there is one)
  only for players with the red cards.

- **withPlayerOffset(playerOffset: { playerId: number; offset: number })** - Use this method to filter decorated players by specific player
  and offset.

  - playerOffset - an object with playerId and an offset number to slice decorated players result with.

  ```sh
  { playerId: number; offset: number }
  ```

- **withStartFromPosition(position)** - Use this method to slice decorated players from specific position. The method will return result if
  the **withPlayerOffset({ playerId: number; offset: number })** method is not called.

  - position - the argument should be a string. Example: 3 - will slice decorated players result (if there is one) from the third player.

- **limitPlayers(number)** - Use this method to return a certain number of decorated players. The method will return result if the
  **withPlayerOffset({ playerId: number; offset: number })** method is not called.

  - number - the argument should be a string. Example: 3 - will return the first three decorated players (if there is one).

- **get()** - returns the built object with decorated players information for the given season.

## Match list module

Initialize module

```sh
const matchListModule = SDK.matchList();
```

### Usage

```sh
matchListModule
  .withSeasonIds([seasonId, seasonId])
  .withRound(round)
  .withTeamIds([teamId, teamId])
  .withTournamentIds([tournamentId, tournamentId])
  .withMatchIds([matchId, matchId])
  .withStartDate(startDate)
  .withEndDate(endDate)
  .withLimit(limit)
  .withOdds({ providersIds: [providerId] })
  .groupMatchesByType(type)
  .withSortDirection(direction)
  .get();
```

Corresponding output should be:

```sh
{
  matchList: MatchModel[],
  odds: { eventId: '', odds: OddsModel},
};
```

Module methods:

- **withSeasonIds(seasonIds)** - The argument should be an array with seasonIds(seasonId: string). Use this method to get matches by
  specific seasons.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withRound(round)** - The argument should be a string (roud: string). Use this method to get matches by specific round.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withTeamIds([teamId, teamId])** - The argument should be an array with teamIds(teamId: string). Use this method to get matches for
  specific team ids.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withTournamentIds([tounamentId, tounamentId])** - The argument should be an array with tounamentIds(tounamentId: string). Use this
  method to get matches for specific tournament ids.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withMatchIds([matchId, matchId])** - The argument should be an array with matchIds (matchId: string). Use this method to get matches by
  specific match ids.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withStartDate(startDate)** - The argument should be a string('YYYY-MM-DD'). Use this method to get matches from specific start date.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withEndDate(endDate)** - The argument should be a string('YYYY-MM-DD'). Use this method to get matches from specific end date.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withLimit(limit)** - The argument should be a string. Use this method to get matches by specific limit.

The method Output is:

```sh
{ matchList: MatchListModel };
```

- **withOdds(options: {providersIds: number[]})**
  - options - the argument is an object where providersIds property should be an array of providers Ids (numbers) to filter odds result.
    Example: [43] - will return available odds data (if there is one) only for odds with the given provider. Example: [] - will return all
    available odds without filtration by providerIds

The method Output is:

```sh
{
  odds: OddsModel,
  markets: marketOptions
}
```

- **groupMatchesByType(type)** - The argument should be a string: (tournament or round). Example: groupMatchesByType(tournament) - Use this
  method to group matches by tournament. Example: groupMatchesByType(round) - Use this method to group matches by round.

#### Usage 1 - groupMatchesByType(tournament)

The method Output is:

```sh
{ matchList: [
	{
		tournament: TournamentMatchModel,
		matchList: MatchModel
	}
] };
```

#### Usage 2 - groupMatchesByType(round)

The method Output is:

```sh
{ matchList: [
	{
		round: round,
		matchList: MatchModel
	}
] };
```

- **withSortDirection(direction)** - The argument should be a string (asc or desc). Use this method to get matches by specific order
  direction.

The method Output is:

```sh
{ matchList: MatchListModel };
```

## Team module

Initialize module

```sh
const teamModule = SDK.team(teamId);
```

**teamId** - the argument is required (teamId: string). It defines the required team.

### Usage

```sh
teamModule
  .withForm(limit)
  .withSquad([position])
  .withNextMatch()
  .withUpcomingMatches(limit, sort)
  .withPreviousMatches(limit, sort)
  .withDates(limit, sort, fromStartTime, toStartTime)
  .withCurrentLeagueStatistics()
  .withSeasons([seasonId])
  .get()
```

Corresponding output should be:

```sh
{
  team: TeamModel,
  squad: PlayerSquadModel[],
  nextMatch: EventModel,
  teamForm: {progres: 10, form: []}
  previousMatches: EventModel[],
  upcomingMatches: EventModel[],
  dateRangeMatches: EventModel[],
  nextMatch: EventModel,
  currentLeagueStatistics: TeamSeasonStatisticsModel,
  seasonsStatistics: TeamSeasonStatisticsModel[],
};
```

Module methods:

- **withForm(limit: number)** - The argument should be a number (limit: number). Use this method to get limited team finished matches with
  their outcomes. The default limit is set to 5 matches.

The method Output is:

```sh
{ teamForm: [{form: {event: EventModel, outcome: 'W'}}] };
```

- **withSquad(positions: string[])** - The positions argument should be an array of strings. The positions array could include some or all
  of the following items: ['keeper', 'midfielder', 'defender', 'forward']. If You do not pass an argument or the array is empty, all the
  players should be returned.

The method Output is:

```sh
{ squad: PlayerSquadModel[] };
```

- **withNextMatch()** - The method returns the next upcomming match for the team.

The method Output is:

```sh
{ nextMatch: EventModel };
```

- **withUpcomingMatches(limit: number, sort?: string)** - The first argument should be a number (limit: number). Use this method to get
  limited team upcoming matches. The default limit is set to 5 matches. The second argument is optional (sort?: string) and with one of the
  following string values: 'asc'/'desc'. The default value is 'asc'. The result does not include postponed matches.

The method Output is:

```sh
{ upcomingMatches: EventModel[] };
```

- **withPreviousMatches(limit: number, sort?: string)** - The first argument should be a number (limit: number). Use this method to get
  limited team finished matches. The default limit is set to 5 matches. The second argument is optional (sort?: string) and with one of the
  following string values: 'asc'/'desc'. The default value is 'desc'. The method Output is:

```sh
{ previousMatches: EventModel[] };
```

- **withDates(config: {limit: number, sort: string, fromStartTime: string, toStartTime: string})** **The config argument has the following
  properties:**

  - limit - a number. The default limit is set to 5 matches.

  - sort - a string with one of the following string values: 'asc'/'desc'. The default value is set to 'asc'.
  - fromStartTime and toStartTime - are strings. They are specifying the desired date range and should be valid dates ISO format
    ('YYYY-MM-DD'). The default values are 10 days before the current date and 20 days after it.

  The method Output is:

```sh
{ dateRangeMatches: EventModel[] };
```

- **withCurrentLeagueStatistics()** - The method returns season statistics for team current league.

The method Output is:

```sh
{ currentLeagueStatistics: TeamSeasonStatisticsModel };
```

- **withSeasons(seasonIds: number[])** - The argument seasonIds[] is required. The method returns statistics for requested seasons. If the
  argument is missing or is empty the output will be an empty array.

The method Output is:

```sh
{ seasonsStatistics: TeamSeasonStatisticsModel[] };
```

## Competition module

Initialize module

```sh
const competitionModule = SDK.competition(tournamentId);
```

**tournamentId** - the argument is required (tournamentId: string). It defines the required tournament.

### Usage

```sh
competitionModule
  .withCurrentSeason()
  .withSeasons([seasonIds])
  .get()
```

Corresponding output should be:

```sh
{
  tournament: TournamentModel
  currentSeason: SeasonModel,
  seasons: SeasonModel[],
};
```

Module methods:

- **withCurrentSeason()** - It will return the last tournament season (active or inactive).

The method Output is:

```sh
{ currentSeason: SeasonModel };
```

- **withSeason(seasonIds: number[])** - The seasonIds argument is optional and should be an array of numbers. If no season ids were passed
  or are an empty array, the output should include all seasons. If there are passed seasons ids, the result should include only them.
- The method Output is:

```sh
{ seasons: SeasonModel[] };
```

## Top Scorers module

Initialize module

```sh
const topScorersModule = SDK.topScorersForSeason(seasonId);
```

**seasonId** - the argument is required (seasonId: string). It defines the required season.

### Usage

```sh
topScorersModule
  .filterByTeams(teamIds)
  .withStartFromPosition(offset)
  .limitTopScorers(limit)
  .get();
```

If the season has top scorers the output should be:

```sh
{ topScorers: TopScorersModel };
```

- **filterByTeams( teamIds )**

  - teamIds(array with numbers) to filter top scorers. Example: [110] - will return available top scorers data (if there is one) only for
    top scorers with the given team.

- **withStartFromPosition( offset )** - Use this method to slice top scorers from specific position.

  - offset - the argument should be a number. Example: 3 - will slice decorated players result (if there is one) from the third player.

- **limitTopScorers( limit )** - Use this method to return a certain number of top scorers.

  - limit - the argument should be a number. Example: 3 - will return the first three top scorers (if there is one).

- **get()** - returns the built object with top scorers information for the given season.

## Season module

Initialize module

```sh
const seasonModule = SDK.season(seasonId);
```

**seasonId** - the argument is required (seasonId: string). It defines the required season.

### Usage

```sh
seasonModule
  .withTopScorers({ offset: 2; teamIds: [id, id]; limit: 10 })
  .get()
```

Corresponding output should be:

```sh
{
  season: SeasonModel,
  topScorersError: TopScorersModel,
};
```

Module methods:

- **withTopScorers({ offset: number; teamIds: number[]; limit: number })** - When Calling this method, we initialize the Top Scorers Module.

```sh
{ topScorersError: TopScorersModel };
```

## Modules Errors

If some of the modules' requests were not successful, the corresponding module should return an error message.

Example:

```sh
{
   commentaryError: "Request failed with status code 500",
   lineupsError: "Request failed with status code 500",
   matchError: "Request failed with status code 500",
   matchEventsError: "Request failed with status code 500",
   oddsError: "Request failed with status code 500",
   standingError: "Request failed with status code 500",
   statsError: "Request failed with status code 500",
   decoratedPlayersForSeasonError: "Request failed with status code 500",
   matchListError: "Request failed with status code 500",
   topScorersError: "Request failed with status code 500",
   ...
}
```

## Module with no data

If the API response has no data, the module should not return anything.