2.0 KiB
2.0 KiB
ts
The ts package makes it easy for users to write functions that can be used in rserve-ts applications.
Installation
You can install the development version of ts from GitHub with:
# install.packages("devtools")
devtools::install_github("tmelliott/ts")
Example
Writing functions is easy, just use the ts_*() functions to define
formals and return types.
# demo.R
library(ts)
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
)
)
# TODO: specify exactly which functions to export in the entry point
# ts_export(app)
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.
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