format_request.R 1.2 KB
Newer Older
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
1

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
2
3
4
5
6
#' API query for SDMX output
#'
#' @param url url to query
#'
#' @return dataframe response
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
7
sdmx_request <- function(url) {
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
8
  as.data.frame(rsdmx::readSDMX(url))
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
9
10
}

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
11
12
13
14
15
#' API query for JSON output
#'
#' @param url url to query
#'
#' @return response: dataframe or list of dataframes
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
16
json_request <- function(url) {
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
17
  jsonlite::fromJSON(rawToChar(httr::GET(url)$content))
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
18
19
}

Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
20
21
22
#' API query for CSV output
#'
#' @param url url to query
23
#' @importFrom utils read.csv
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
24
25
#'
#' @return dataframe response
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
26
27
csv_request <- function(url) {
  read.csv(url)
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
28
29
30
31
32
33
34
35
}

# Request function based on expected response
REQUEST_FUNCTION_MAPPING <- hash::hash(
  "SDMX-ML" = sdmx_request,
  "JSON" = json_request,
  "CSV" = csv_request
)
36
37
38


#' Transform a hash object into a string of parameters
Pauline Maury Laribière's avatar
Pauline Maury Laribière committed
39
40
#' hash::hash("a" = list("1"), "b" = list("2", "3"))
#' becomes "a=1&b=2&b=3"
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#'
#' @param filters hash object
#'
#' @return formatted string of parameters
hash_to_string <- function(filters) {
  string <- ""
  for (prop in ls(filters)) {
    for (value in filters[[prop]]) {
      if (string == "") {
        string <- glue::glue("{prop}={value}")
      } else {
        string <- paste(string, glue::glue("{prop}={value}"), sep = "&")
      }
    }
  }
  string
57
}