githubEdit

Tutorial: Stof + TypeScript Config

Simple, self-validating config using Stof + TypeScript

In our hypothetical scenario, we have a server that is running a configurable environment for clients. We'll use Stof as the glue between systems to ensure our environment can be safely configured from afar.

Defining a Simple Config & Testing in TypeScript

/*!
 * Simple Server Config (Stof).
 */

// semantic versions are a primitive type in Stof
version: 0.1.0-server.example
server: {
    name: "www.example.com:80"
    root_dir: "/etc/httpd"
    ms timeout: 3s
    bool keep_alive: true
    ms keep_alive_timeout: 5s
    GiB ram: 32GiB
    
    // single valid check to start
    fn valid() -> bool {
        self.ram > 2GiB &&
        (!self.keep_alive || self.keep_alive_timeout > 100ms) &&
        self.timeout > 100ms &&
        self.name.len() > 0 &&
        self.root_dir.len() > 0
    }
}

We'll use TypeScript and the JSR package to test our valid function:

Run with deno run or your preferred JS runtime. Now set the timeout to 0 and run again to see "false".

circle-info

If you don't want to use TypeScript, you can use the CLI or the online playgroundarrow-up-right for this tutorial, using the Stof directly (not as a string within TS).

Apply the Server Config

Next, let's add a simple Server.apply library function so that our server can apply the desired settings.

Stof Endpoint Handler

Now that we have a very basic setup, let's add a function that mimics an endpoint handler that takes some Stof.

Let's also move the apply logic to an "apply" function within the server's base Stof config, only calling the Server.apply lib function when the configuration is valid.

Stof Schema & Type

Let's use some Stof features to clean this up a bit and formalise our configuration.

Up until now, our workflow is very similar to a config written in JSON, TOML, YAML, etc. Using Stof's type system with a couple Obj library functions (run & schemafy), we can create self-validating types that can be composed, extended, etc.

circle-info

See Schemas for a more in-depth look at Obj.schemafy, and Object Run for a more in-depth look at Obj.run.

Completed Example

Here is the completed example as just Stof (minus the Server.apply TS lib function). Paste into the online playgroundarrow-up-right and run to try for yourself.

Next Steps

Now that you have a foundation, play around with a few practical next steps:

  • Persistent base configuration Stof document instead of a string in TS

    • Prevents having to parse the base config type, libs, etc. each time

  • Use imported TOML, JSON, or YAML for base configuration values

  • Create more specific apply functions and/or a complete server Stof API

  • Try using the CLI, Rust, or the online playground with these new concepts

Last updated