Skip to content

JS/TS APIs

You can place JavaScript and TypeScript into traildepot/scripts and TrailBase will automatically load them on startup. For now we support custom HTTP handlers letting you register routes, act on requests, query the database and build arbitrary responses.

Runtime

Before we jump into details, let’s quickly talk about the runtime itself. At its heart, it’s a pool of V8-js-engines alongside a runtime that supports basic tasks such as file I/O, web requests, timers, etc. However, it is not a complete Node.js runtime, at least for now, since it would pull in a lot of extra dependencies. Note further, that the pool of workers/isolates does not share state, i.e. you cannot use global state to reliably share state across requests. You should rely on the database for persisting and sharing state.

HTTP Endpoints

The following example illustrates a few things:

  • Hot to register a parameterized route with :table.
  • How implement a handler that returns text/plain content. There is also jsonHandler and htmlHandler.
  • How to query the database.
  • How to return an error.
import {
addRoute,
query,
stringHandler,
HttpError,
StatusCodes
} from "../trailbase.js";
addRoute("GET", "/test/:table", stringHandler(async (req) => {
const table = req.params["table"];
if (table) {
const rows = await query(`SELECT COUNT(*) FROM ${table}`, [])
return `entries: ${rows[0][0]}`;
}
throw new HttpError(StatusCodes.BAD_REQUEST, "Missing '?table=' search query parm");
}));

More examples can be found in the repository in client/testfixture/scripts/index.ts.