The RserveTS package makes it easy for users to write functions that can be used in rserve-ts applications.
You can install the development version of RserveTS from
GitHub with:
# install.packages("devtools")
devtools::install_github("tmelliott/RserveTS")Writing functions is easy, just use the ts_*() functions
to define formals and return types.
# demo.R
library(RserveTS)
addFn <- ts_function(
function(a = ts_numeric(1), b = ts_numeric(1)) a + b,
result = ts_numeric(1)
)
sampleFn <- ts_function(
function(x = ts_character(), n = ts_integer(1)) sample(x, n),
result = ts_character()
)
app <- ts_function(
function() {
list(
add = addFn,
sample = sampleFn
)
},
result = ts_list(
add = addFn,
sample = sampleFn
)
)Then use ts_compile() to generate the TypeScript
schemas:
import { Robj } from 'rserve-ts';
import { z } from 'zod';
const addFn = Robj.ocap([z.number(), z.number()], Robj.numeric(1));
const app = Robj.ocap([],
Robj.list({
add: Robj.ocap(),
sample: Robj.ocap()
})
);
const sampleFn = Robj.ocap(
[z.union([z.string(), z.array(z.string())]), z.number()],
Robj.character()
);
export default {
addFn,
app,
sampleFn
};You can then import this into your rserve-ts
application. See tests/testthat/sampler for an example.
Generated .ts files are a single long line per export by
default. If you have npm available, install Prettier in your app project
(recommended: dev dependency) so npx prettier works from
that directory:
npm install --save-dev prettierWith prettier or npx on your
PATH, enable formatting for a session (or pass
format = TRUE per call):
options(RserveTS.format = TRUE)
options(RserveTS.prettier_cmd = c("prettier", "--parser", "typescript"))
# or: options(RserveTS.prettier_cmd = c("npx", "--yes", "prettier", "--parser", "typescript"))
ts_compile(f) # returns a multi-line string
ts_compile("app.R", filename = "app.rserve") # writes a formatted .ts filemake site turns on RserveTS.format so
reference examples render prettily. You can still override the CLI with
RserveTS_PRETTIER_CMD (space-separated tokens) or
options(RserveTS.prettier_cmd = ...). When neither is set,
the package looks for prettier / npx prettier
on PATH.
The package writes generated source to a temporary .ts
file and runs your command with that path as the last
argument, as Prettier does for prettier file.ts. Another
CLI (e.g. Biome) can be used if it
supports the same “format this file path” pattern.
It is also possible to generate a sourceable file to deploy an Rserve
instance with your app code using ts_deploy():
ts_deploy(app)
# run with: Rscript app.rserve.R