R/get_games.R

#' Returns a data frame with games from a season
#'
#' @param season Season to be used, i.e. '2015' for the SHL season 2015/2016
#' @param team_id If you only want the games for one team you can pass their team_id here, i.e. "FBK"
#' @param acces_token an access_token generated by get_shl_access_token()
#' @export
#' @examples
#' \dontrun{
#' get_teams()
#' }

get_games <- function(season = season, team_id = NULL,
                      access_token = get_shl_access_token()) {

  # Search SHL API for top players
  res <- GET(url = stringr::str_glue('https://openapi.shl.se/seasons/{season}/games'),
             query = list("teamIds[]" = team_id),
             add_headers(Authorization = paste("Bearer", access_token, sep = " "))) %>%
    content()


  if (!is.null(res$error)) {
    stop(str_glue('{res$error$message} ({res$error$status})'))
  }

  num_loops <- seq_len(length(res))

  games <- purrr::map_df(num_loops, function(this_row){
    this_game <- res[[this_row]]

    start_date_time <- stringr::str_replace(this_game$start_date_time, "T", " ")

    list(
      away_team_code = this_game$away_team_code,
      away_team_result = this_game$away_team_result,
      game_center = this_game$game_center_active,
      game_id = this_game$game_id,
      game_type = this_game$game_type,
      game_uuid = this_game$game_uuid,
      highlights_coverage_enabled = this_game$highlights_coverage_enabled,
      home_team_code = this_game$home_team_code,
      home_team_result = this_game$home_team_result,
      live_coverage_enabled = this_game$live_coverage_enabled,
      overtime = this_game$overtime,
      penalty_shots = this_game$penalty_shots,
      played = this_game$played,
      season = this_game$season,
      series = this_game$series,
      date = stringr::str_sub(start_date_time, 1, 10),
      start_time = stringr::str_sub(start_date_time, 12, 19))
  }) %>%
    dplyr::mutate(date = as.Date(date),
                  start_time = chron::chron(times = start_time))

  return(games)
}
filipwastberg/shlr documentation built on May 17, 2019, 1:14 a.m.