Shiny app startup options

Using parseQueryString in conjunction with session$clientData$url_search can be used to pass variables to a shiny app from the url address. It can also be used with Sys.getenv('SHINY_PORT') to follow programming paths based on variable values and execution environment. In the example below, the code points to different instances of a database, depending on user-specification and execution environment. Running locally or on the server points to different default databases and includes the ability to override. This code is useful when placed at the top of an app during development.

 1library(shiny)
 2
 3## allowed_databases stores the names of the allowable databases
 4allowed_databases <- c('test', 'production', 'uploadtest')
 5
 6## default database names for interactive and server modes
 7dafault_interactive <- 'test'
 8dafault_server <- 'production'
 9
10## override database defaults for interactive mode
11## to override the default database set override_default_database to TRUE and 
12## override_use_database to the database name
13override_default_database <- FALSE
14override_use_database <- 'production'
15
16server <- function(input, output, session) {
17  
18  val <- reactiveValues(db = NULL)
19  
20  db_set_database <- function(name) {
21    val$db <- name
22  }
23  
24  ## set database
25  observe({
26    if(Sys.getenv('SHINY_PORT') == "") {
27      ## if running locally then use test database unless override set
28      if (override_default_database) {
29        ## run against specified instance
30        if (!override_use_database %in% allowed_databases) override_use_database <- dafault_interactive
31        db_set_database(override_use_database)
32      } else {
33        ## run against default interactive instance
34        db_set_database(dafault_interactive)
35      }
36    } else {
37      ## if running on server then look for database in url
38      query <- parseQueryString(session$clientData$url_search)
39      if (!is.null(query[['database']])) {
40        ## get database name from url and check that it is in the list of allowed database names
41        my_database <- tolower(query[['database']])
42        if (!my_database %in% allowed_databases) my_database <- dafault_server
43        ## run against selected instance
44        db_set_database(my_database)
45      } else {
46        ## default - run against defaukt server instance
47        db_set_database(dafault_server)
48      }
49    }
50  })
51  
52  output$txt1 <- renderPrint(paste0('Using database ', val$db))
53  
54}
55
56ui <- fluidPage(
57  verbatimTextOutput('txt1')
58)
59
60shinyApp(ui, server)