The RserveTS package makes it easy for users to write functions that can be used in rserve-ts applications.
install.packages("RserveTS")
You can install the development version of RserveTS from
GitHub with:
# install.packages("devtools")
# devtools::install_github("tmelliott/RserveTS")
install.packages("RserveTS", repos = c('https://tmelliott.r-universe.dev', 'https://cloud.r-project.org'))
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 prettier
With prettier or npx on your PATH, pass format = TRUE when
compiling a file:
ts_compile("app.R", filename = "app.rserve", format = TRUE)
You can point to a specific formatter with prettier_cmd (full argv,
executable first), the R option RserveTS.prettier_cmd, or the
environment variable RserveTS_PRETTIER_CMD (space-separated tokens).
The package writes the 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