-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse_rt_response.R
60 lines (53 loc) · 1.66 KB
/
parse_rt_response.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#' Parse an RT response in its parts as a list
#'
#' The RT API uses overrides default HTTP behavior with their own set of status
#' codes, messages, and response formats. This function parses that custom
#' implementation and presents it into something that's easier to build a
#' package with.
#'
#' For example, a response like:
#'
#' "RT/4.4.3 200 Ok
#'
#' # Ticket 2 created.
#'
#' "
#'
#' is turned into the list:
#'
#' $status
#' [1] 200
#'
#' $message
#' [1] "Ok"
#'
#' $body
#' [1] "# Ticket 2 created."
#'
#' @param response (character) Parsed response from \code{\link[httr]{content}}
#' @param verbose (logical) Optional, defaults to \code{TRUE}. Prints more information during parsing.
#'
#' @return (list) List with named elements status, message, and body
parse_rt_response <- function(response, verbose = FALSE) {
split_response <- stringr::str_split(response, "[\\n]+", n = 2)
# Response should be a single result, with parts for the first line, and rest
stopifnot(length(split_response) == 1 &&
length(split_response[[1]] != 2))
first <- split_response[[1]][1]
rest <- stringr::str_replace_all(split_response[[1]][2], "[\\n]+$", "")
# Parse the first line (RT version + HTTP status + custom status messsage)
match <- stringr::str_match(first, "\\ART/[\\d\\.]+ (\\d+) (.+)\\Z")
# Stop, helpfully, if we failed to get what we expected from the regex
if (!all(dim(match) == c(1, 3))) {
if (verbose) {
message(content)
}
message("Failed to parse RT response. Returning response directly from httr.")
return(response)
}
return(list(
status = as.numeric(match[1,2]),
message = match[1,3],
body = rest
))
}