JS20

Documentation

JS20 - Documentation

Endpoints

Here's how to define an endpoint.

import { sInteger } from '@js20/schema';

interface Input {
    a: number;
    b: number;
}

interface Output {
    sum: number;
}

const sInput: Input = {
    a: sInteger().type(),
    b: sInteger().type(),
};

const sOutput: Output = {
    sum: sInteger().type(),
};

app.addEndpoint({
    method: 'POST',
    path: '/sum',
    inputSchema: sInput,
    outputSchema: sOutput,
    isLoggedIn: false,
    run: (_system, { a, b }) => {
        // a and b are guaranteed to be integers here
        // returning anything else than the output format would error
        return { sum: a + b };
    }
});

What's happening here?

  • We create our Input type that accepts two numbers: a & b
  • We create our Output type that returns a single number: sum
  • We create Schemas that validate input & output in runtime
  • Then we register our endpoint POST /sum that returns sum = a + b
  • We don't have to validate user input, since it automatically validates against the schema
  • isLoggedIn: false means this endpoint is public and doesn't require authentication
JS20