-
Notifications
You must be signed in to change notification settings - Fork 258
Expand file tree
/
Copy pathparse-query.R
More file actions
259 lines (223 loc) · 6.65 KB
/
Copy pathparse-query.R
File metadata and controls
259 lines (223 loc) · 6.65 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
queryStringFilter <- function(req){
handled <- req$.internal$queryStringHandled
if (is.null(handled) || handled != TRUE) {
qs <- req$QUERY_STRING
args <- parseQS(qs)
req$args <- c(req$args, args)
req$argsQuery <- args
req$.internal$queryStringHandled <- TRUE
}
forward()
}
#' @noRd
parseQS <- function(qs){
if (is.null(qs) || length(qs) == 0L || qs == "") {
return(list())
}
# Looked into using webutils::parse_query()
# Currently not pursuing `webutils::parse_query` as it does not handle Encoding issues handled below
# (Combining keys are also not handled by `webutils::parse_query`)
qs <- stri_replace_first_regex(qs, "^[?]", "")
qs <- chartr("+", " ", qs)
args <- stri_split_fixed(qs, "&", omit_empty = TRUE)[[1L]]
kv <- lapply(args, function(x) {
# returns utf8 strings
httpuv::decodeURIComponent(stri_split_fixed(x, "=", omit_empty = TRUE)[[1]])
})
kv <- kv[vapply(kv, length, numeric(1)) == 2] # Ignore incompletes
if (length(kv) == 0) {
# return a blank list of args if there is nothing to parse
return(list())
}
keys <- vapply(kv, `[`, character(1), 1)
kenc <- unique(Encoding(keys))
if (any(kenc != "unknown")) {
# https://github.com/rstudio/plumber/pull/314#discussion_r239992879
non_ascii <- setdiff(kenc, "unknown")
warning(
"Query string parameter received in non-ASCII encoding. Received: ",
paste0(non_ascii, collapse = ", ")
)
}
vals <- lapply(kv, `[`, 2)
names(vals) <- keys
# If duplicates, combine
combine_keys(vals, type = "query")
}
createPathRegex <- function(pathDef, funcParams = NULL){
# Create a regex from the defined path, substituting variables where appropriate
match <- stri_match_all(
pathDef,
# capture any plumber type (<arg:TYPE>).
# plumberToApiType(types) will yell if it is unknown
# and can not be guessed from endpoint function args)
# <arg> will be given the TYPE `defaultApiType`
regex = "/<(\\.?[a-zA-Z][\\w_\\.]*)(?::([^>]*))?>"
)[[1]]
names <- match[,2]
# No path params
if (length(names) <= 1 && is.na(names)) {
return(
list(
names = character(),
types = NULL,
regex = paste0("^", pathDef, "$"),
converters = NULL,
areArrays = NULL
)
)
}
plumberTypes <- stri_replace_all(match[,3], "$1", regex = "^\\[([^\\]]*)\\]$")
if (length(funcParams) > 0) {
# Override with detection of function args if type not found in map
idx <- !(plumberTypes %in% names(plumberToApiTypeMap))
plumberTypes[idx] <- sapply(funcParams, `[[`, "type")[names[idx]]
}
apiTypes <- plumberToApiType(plumberTypes, inPath = TRUE)
areArrays <- stri_detect_regex(match[,3], "^\\[[^\\]]*\\]$")
if (length(funcParams) > 0) {
# Override with detection of function args when false or na
idx <- (is.na(areArrays) | !areArrays)
areArrays[idx] <- sapply(funcParams, `[[`, "isArray")[names[idx]]
}
areArrays[is.na(areArrays)] <- defaultIsArray
pathRegex <- pathDef
regexps <- typesToRegexps(apiTypes, areArrays)
for (regex in regexps) {
pathRegex <- stri_replace_first_regex(
pathRegex,
pattern = "/(?:<\\.?[a-zA-Z][\\w_\\.:\\[\\]]*>)(/?)",
replacement = paste0("/(", regex, ")$1")
)
}
list(
names = names,
types = apiTypes,
regex = paste0("^", pathRegex, "$"),
converters = typesToConverters(apiTypes, areArrays),
areArrays = areArrays
)
}
typesToRegexps <- function(apiTypes, areArrays = FALSE) {
# return vector of regex strings
mapply(
function(x, y) {x[[y]]},
apiTypesInfo[apiTypes],
ifelse(areArrays, "regexArray", "regex"),
USE.NAMES = FALSE
)
}
typesToConverters <- function(apiTypes, areArrays = FALSE) {
# return list of functions
mapply(
function(x, y) {x[[y]]},
apiTypesInfo[apiTypes],
ifelse(areArrays, "converterArray", "converter"),
USE.NAMES = FALSE
)
}
# Extract the params from a given path
# @param def is the output from createPathRegex
extractPathParams <- function(def, path){
vals <- as.list(stri_match(path, regex = def$regex)[,-1])
names(vals) <- def$names
if (!is.null(def$converters)){
# Run each value through its converter
for (i in 1:length(vals)){
vals[[i]] <- def$converters[[i]](vals[[i]])
}
}
vals
}
#' combine args that share the same name
#' @noRd
#' @importFrom stats setNames
combine_keys <- function(obj, type) {
keys <- names(obj)
unique_keys <- unique(keys)
# If a query string as the same amount of unique keys as keys,
# then return it as it
# (`"multi"` type objects MUST be processed, regardless if the unique key count is the same)
if (
length(unique_keys) == length(keys) &&
identical(type, "query")
) {
return(obj)
}
vals <- unname(obj)
cleanup_item <- switch(
type,
"query" =
function(x) {
unname(unlist(x))
},
"multi" =
function(x) {
if (length(x) == 1) {
part <- x[[1]]
filename <- part$filename
parsed <- part$parsed
if (!is.null(filename)) {
# list(
# "myfile.json" = list(
# a = 1, b = 2
# )
# )
return(
setNames(
list(parsed),
filename
)
)
}
# list(
# a = 1, b = 2
# )
return(parsed)
}
# length is > 1
has_a_filename <- FALSE
filenames <- lapply(x, function(part) {
filename <- part$filename
if (is.null(filename)) return("")
has_a_filename <<- TRUE
filename
})
parsed_items <- lapply(unname(x), `[[`, "parsed")
if (!has_a_filename) {
# return as is
return(parsed_items)
}
return(setNames(parsed_items, filenames))
},
stop("unknown type: ", type)
)
# equivalent code output, `split` is much faster with larger objects
# Testing on personal machine had a breakpoint around 150 letters as query parameters
## n <- 150
## k <- sample(letters, n, replace = TRUE)
## v <- as.list(sample(1L, n, replace = TRUE))
## microbenchmark::microbenchmark(
## split = {
## lapply(split(v, k), function(x) unname(unlist(x)))
## },
## not_split = {
## lapply(unique(k), function(x) {
## unname(unlist(v[k == x]))
## })
## }
## )
vals <-
if (length(unique_keys) > 150) {
lapply(split(vals, keys), function(items) {
cleanup_item(items)
})
} else {
# n < 150
lapply(unique_keys, function(key) {
cleanup_item(vals[keys == key])
})
}
names(vals) <- unique_keys
vals
}