-
-
Save jnolis/0123a79ca2758bc1170f721f23729f8c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(shiny) | |
library(jsonlite) | |
# we'll store received data in a local json file | |
write_json(list(), "data.json") | |
post_handler <- function(req, response) { | |
# we'll catch everything that's POST for this demo but you'll want to make | |
# sure you don't step on shiny's built-in POST handlers | |
# (I'm pretty sure this handler is called after shiny's handlers but :shrug:) | |
if (identical(req$REQUEST_METHOD, "POST")) { | |
# you probably want to limit the upload file size w/ the first arg of $read() | |
data <- req$rook.input$read() | |
data <- jsonlite::fromJSON(rawToChar(data)) | |
message(str(data)) | |
if (is.null(data$token) || is.null(data$name)) { | |
# expect a token and a name for this demo but you'd want to do auth/routing here... | |
# if the request is bad return the base response of 404 not found | |
return(response) | |
} else { | |
# update our local data store (or write to db etc) | |
y <- list() | |
y[[data$token]] <- data$name | |
x <- utils::modifyList(read_json("data.json"), y, keep.null = TRUE) | |
write_json(x, "data.json") | |
# return all okay response! | |
return(shiny:::httpResponse(200, "text/plain", "OK\n")) | |
} | |
} | |
# return regular shiny response | |
response | |
} | |
options(shiny.http.response.filter = post_handler) | |
ui <- fluidPage( | |
h2("Hello", uiOutput("name", inline = TRUE, container = span)) | |
) | |
server <- function(input, output, session) { | |
# poll our data store (local json) for updates, using token as ID | |
names_list <- reactiveFileReader(1000, session, "data.json", function(x) { | |
read_json(x) | |
}) | |
output$name <- renderUI({ | |
query <- getQueryString() | |
if (!is.null(query$token) && query$token %in% names(names_list())) { | |
paste0(names_list()[[query$token]],"!") | |
} else { | |
"..." | |
} | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment