/
finbif_update_cache.R
78 lines (45 loc) · 1.49 KB
/
finbif_update_cache.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#' Update cache
#'
#' Update all cached API requests from FinBIF.
#'
#' @aliases fb_update_cache
#'
#' @examples \dontrun{
#'
#' finbif_update_cache()
#'
#' }
#' @export
finbif_update_cache <- function() {
fcp <- getOption("finbif_cache_path")
if (is.null(fcp)) {
for (cached_object in as.list(cache_location)) {
is_swagger <- isTRUE(cached_object[["swagger"]])
can_be_updated <- !is.character(cached_object[["data"]]) && !is_swagger
if (can_be_updated) {
api_get(cached_object[["data"]])
}
}
} else if (is.character(fcp)) {
for (cached_object in list.files(fcp, pattern = "finbif_cache_file_")) {
cached_object <- file.path(fcp, cached_object)
cached_object <- readRDS(cached_object)
api_get(cached_object)
}
} else {
has_dbi <- has_pkgs("DBI", "blob")
stopifnot("Packages {DBI} & {blob} needed to use a DB cache" = has_dbi)
if (DBI::dbExistsTable(fcp, "finbif_cache")) {
cached_objects <- DBI::dbGetQuery(fcp, "SELECT hash FROM finbif_cache")
for (i in cached_objects[["hash"]]) {
db_query_i <- sprintf("SELECT * FROM finbif_cache WHERE hash = '%s'", i)
db_cache <- DBI::dbGetQuery(fcp, db_query_i)
created <- as.POSIXct(db_cache[["created"]], origin = "1970-01-01")
last_cache_ind <- which.max(created)[[1L]]
cached_object <- unserialize(db_cache[last_cache_ind, "blob"][[1L]])
api_get(cached_object)
}
}
}
invisible(NULL)
}