% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/app.R
\name{new_app}
\alias{new_app}
\alias{webfakes_app}
\title{Create a new web application}
\usage{
new_app()
}
\value{
A new \code{webfakes_app}.
}
\description{
Create a new web application
}
\details{
The typical workflow of creating a web application is:
\enumerate{
\item Create a \code{webfakes_app} object with \code{new_app()}.
\item Add middleware and/or routes to it.
\item Start is with the \code{webfakes_app$listen()} method, or start it in
another process with \code{\link[=new_app_process]{new_app_process()}}.
\item Make queries to the web app.
\item Stop it via \code{CTRL+C} / \code{ESC}, or, if it is running in another
process, with the \verb{$stop()} method of \code{\link[=new_app_process]{new_app_process()}}.
}

A web application can be
\itemize{
\item restarted,
\item saved to disk,
\item copied to another process using the callr package, or a similar way,
\item embedded into a package,
\item extended by simply adding new routes and/or middleware.
}

The webfakes API is very much influenced by the
\href{http://expressjs.com/}{express.js} project.
\subsection{Create web app objects}{

\if{html}{\out{<div class="sourceCode r">}}\preformatted{new_app()
}\if{html}{\out{</div>}}

\code{new_app()} returns a \code{webfakes_app} object the has the methods listed
on this page.

An app is an environment with S3 class \code{webfakes_app}.
}

\subsection{The handler stack}{

An app has a stack of handlers. Each handler can be a route or
middleware. The differences between the two are:
\itemize{
\item A route is bound to one or more paths on the web server. Middleware
is not (currently) bound to paths, but run for all paths.
\item A route is usually (but not always) the end of the handler stack for
a request. I.e. a route takes care of sending out the response to
the request. Middleware typically performs some action on the request
or the response, and then the next handler in the stack is invoked.
}
}

\subsection{Routes}{

The following methods define routes. Each method corresponds to the
HTTP verb with the same name, except for \code{app$all()}, which creates a
route for all HTTP methods.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$all(path, ...)
app$delete(path, ...)
app$get(path, ...)
app$head(path, ...)
app$patch(path, ...)
app$post(path, ...)
app$put(path, ...)
... (see list below)
}\if{html}{\out{</div>}}
\itemize{
\item \code{path} is a path specification, see 'Path specification' below.
\item \code{...} is one or more handler functions. These will be placed in the
handler stack, and called if they match an incoming HTTP request.
See 'Handler functions' below.
}

webfakes also has methods for the less frequently used HTTP verbs:
\code{CONNECT}, \code{MKCOL}, \code{OPTIONS}, \code{PROPFIND}, \code{REPORT}. (The method
names are always in lowercase.)

If a request is not handled by any routes (or handler functions in
general), then webfakes will send a simple HTTP 404 response.
}

\subsection{Middleware}{

\code{app$use()} adds a middleware to the handler stack. A middleware is
a handler function, see 'Handler functions' below. webfakes comes with
middleware to perform common tasks:
\itemize{
\item \code{\link[=mw_etag]{mw_etag()}} adds an \code{Etag} header to the response.
\item \code{\link[=mw_log]{mw_log()}} logs each requests to standard output, or another connection.
\item \code{\link[=mw_raw]{mw_raw()}} parses raw request bodies.
\item \code{\link[=mw_text]{mw_text()}} parses plain text request bodies.
\item \code{\link[=mw_json]{mw_json()}} parses JSON request bodies.
\item \code{\link[=mw_multipart]{mw_multipart()}} parses multipart request bodies.
\item \code{\link[=mw_static]{mw_static()}} serves static files from a directory.
\item \code{\link[=mw_urlencoded]{mw_urlencoded()}} parses URL encoded request bodies.
}

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$use(..., .first = FALSE)
}\if{html}{\out{</div>}}
\itemize{
\item \code{...} is a set of (middleware) handler functions. They are added to
the handler stack, and called for every HTTP request. (Unless an HTTP
response is created before reaching this point in the handler stack.)
\item \code{.first} set to \code{TRUE} is you want to add the handler function
to the bottom of the stack.
}
}

\subsection{Handler functions}{

A handler function is a route or middleware. A handler function is
called by webfakes with the incoming HTTP request and the outgoing
HTTP response objects (being built) as arguments. The handler function
may query and modify the members of the request and/or the response
object. If it returns the string \code{"next"}, then it is \emph{not} a terminal
handler, and once it returns, webfakes will move on to call the next
handler in the stack.

A typical route:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$get("/user/:id", function(req, res) \{
  id <- req$params$id
  ...
  res$
    set_status(200L)$
    set_header("X-Custom-Header", "foobar")$
    send_json(response, auto_unbox = TRUE)
\})
}\if{html}{\out{</div>}}
\itemize{
\item The handler belongs to an API path, which is a wildcard path in
this case. It matches \verb{/user/alice}, \verb{/user/bob}, etc. The handler
will be only called for GET methods and matching API paths.
\item The handler receives the request (\code{req}) and the response (\code{res}).
\item It sets the HTTP status, additional headers, and sends the data.
(In this case the \code{webfakes_response$send_json()} method automatically
converts \code{response} to JSON and sets the \code{Content-Type} and
\code{Content-Length} headers.
\item This is a terminal handler, because it does \emph{not} return \code{"next"}.
Once this handler function returns, webfakes will send out the HTTP
response.
}

A typical middleware:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$use(function(req, res) \{
  ...
  "next"
\})
}\if{html}{\out{</div>}}
\itemize{
\item There is no HTTP method and API path here, webfakes will call the
handler for each HTTP request.
\item This is not a terminal handler, it does return \code{"next"}, so after it
returns webfakes will look for the next handler in the stack.
}
}

\subsection{Errors}{

If a handler function throws an error, then the web server will return
a HTTP 500 \code{text/plain} response, with the error message as the
response body.
}

\subsection{Request and response objects}{

See \link{webfakes_request} and \link{webfakes_response} for the methods of the
request and response objects.
}

\subsection{Path specification}{

Routes are associated with one or more API paths. A path specification
can be
\itemize{
\item A "plain" (i.e. without parameters) string. (E.g. \code{"/list"}.)
\item A parameterized string. (E.g. \code{"/user/:id"}.)
\item A regular expression created via \code{\link[=new_regexp]{new_regexp()}} function.
\item A list or character vector of the previous ones. (Regular expressions
must be in a list.)
}
}

\subsection{Path parameters}{

Paths that are specified as parameterized strings or regular expressions
can have parameters.

For parameterized strings the keys may contain letters, numbers and
underscores. When webfakes matches an API path to a handler with a
parameterized string path, the parameters will be added to the
request, as \code{params}. I.e. in the handler function (and subsequent
handler functions, if the current one is not terminal), they are
available in the \code{req$params} list.

For regular expressions, capture groups are also added as parameters.
It is best to use named capture groups, so that the parameters are in
a named list.

If the path of the handler is a list of parameterized strings or
regular expressions, the parameters are set according to the first
matching one.
}

\subsection{Templates}{

webfakes supports templates, using any template engine. It comes with
a template engine that uses the glue package, see \code{\link[=tmpl_glue]{tmpl_glue()}}.

\code{app$engine()} registers a template engine, for a certain file
extension. The \verb{$render()} method of \link{webfakes_response}
can be called from the handler function to evaluate a template from a
file.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$engine(ext, engine)
}\if{html}{\out{</div>}}
\itemize{
\item \code{ext}: the file extension for which the template engine is added.
It should not contain the dot. E.g. \verb{"html"', }"brew"`.
\item \code{engine}: the template engine, a function that takes the file path
(\code{path}) of the template, and a list of local variables (\code{locals})
that can be used in the template. It should return the result.
}

An example template engine that uses glue might look like this:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$engine("txt", function(path, locals) \{
  txt <- readChar(path, nchars = file.size(path), useBytes = TRUE)
  glue::glue_data(locals, txt)
\})
}\if{html}{\out{</div>}}

(The built-in \code{\link[=tmpl_glue]{tmpl_glue()}} engine has more features.)

This template engine can be used in a handler:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$get("/view", function(req, res) \{
 txt <- res$render("test")
 res$
   set_type("text/plain")$
   send(txt)
\})
}\if{html}{\out{</div>}}

The location of the templates can be set using the \code{views} configuration
parameter, see the \verb{$set_config()} method below.

In the template, the variables passed in as \code{locals}, and also the
response local variables (see \code{locals} in \link{webfakes_response}), are
available.
}

\subsection{Starting and stopping}{

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$listen(port = NULL, opts = server_opts(), cleanup = TRUE)
}\if{html}{\out{</div>}}
\itemize{
\item \code{port}: port to listen on. When \code{NULL}, the operating system will
automatically select a free port.
\item \code{opts}: options to the web server. See \code{\link[=server_opts]{server_opts()}} for the
list of options and their default values.
\item \code{cleanup}: stop the server (with an error) if the standard input
of the process is closed. This is handy when the app runs in a
\code{callr::r_session} subprocess, because it stops the app (and the
subprocess) if the main process has terminated.
}

This method does not return, and can be interrupted with \code{CTRL+C} / \code{ESC}
or a SIGINT signal. See \code{\link[=new_app_process]{new_app_process()}} for interrupting an app that
is running in another process.

When \code{port} is \code{NULL}, the operating system chooses a port where the
app will listen. To be able to get the port number programmatically,
before the listen method blocks, it advertises the selected port in a
\code{webfakes_port} condition, so one can catch it:

webfakes by default binds only to the loopback interface at 127.0.0.1, so
the webfakes web app is never reachable from the network.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{withCallingHandlers(
  app$listen(),
  "webfakes_port" = function(msg) print(msg$port)
)
}\if{html}{\out{</div>}}
}

\subsection{Logging}{

webfakes can write an access log that contains an entry for all incoming
requests, and also an error log for the errors that happen while
the server is running. This is the default behavior for local app
(the ones started by \code{app$listen()} and for remote apps (the ones
started via \code{new_app_process()}:
\itemize{
\item Local apps do not write an access log by default.
\item Remote apps write an access log into the
\verb{<tmpdir>/webfakes/<pid>/access.log} file, where \verb{<tmpdir>} is the
session temporary directory of the \emph{main process}, and \verb{<pid>} is
the process id of the \emph{subprocess}.
\item Local apps write an error log to \verb{<tmpdir>/webfakes/error.log}, where
\verb{<tmpdir>} is the session temporary directory of the current process.
\item Remote app write an error log to the \verb{<tmpdir>/webfakes/<pid>/error.log},
where \verb{<tmpdir>} is the session temporary directory of the
\emph{main process} and \verb{<pid>} is the process id of the \emph{subprocess}`.
}

See \code{\link[=server_opts]{server_opts()}} for changing the default logging behavior.
}

\subsection{Shared app data}{

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$locals
}\if{html}{\out{</div>}}

It is often useful to share data between handlers and requests in an
app. \code{app$locals} is an environment that supports this. E.g. a
middleware that counts the number of requests can be implemented as:

\if{html}{\out{<div class="sourceCode">}}\preformatted{app$use(function(req, res) \{
  locals <- req$app$locals
  if (is.null(locals$num)) locals$num <- 0L
  locals$num <- locals$num + 1L
  "next"
\})
}\if{html}{\out{</div>}}

\link{webfakes_response} objects also have a \code{locals} environment, that is
initially populated as a copy of \code{app$locals}.
}

\subsection{Configuration}{

\if{html}{\out{<div class="sourceCode r">}}\preformatted{app$get_config(key)
app$set_config(key, value)
}\if{html}{\out{</div>}}
\itemize{
\item \code{key}: configuration key.
\item \code{value}: configuration value.
}

Currently used configuration values:
\itemize{
\item \code{views}: path where webfakes searches for templates.
}
}
}
\examples{
# see example web apps in the `/examples` directory in
system.file(package = "webfakes", "examples")

app <- new_app()
app$use(mw_log())

app$get("/hello", function(req, res) {
  res$send("Hello there!")
})

app$get(new_regexp("^/hi(/.*)?$"), function(req, res) {
  res$send("Hi indeed!")
})

app$post("/hello", function(req, res) {
  res$send("Got it, thanks!")
})

app

# Start the app with: app$listen()
# Or start it in another R session: new_app_process(app)
}
\seealso{
\link{webfakes_request} for request objects, \link{webfakes_response} for
response objects.
}
