functions
Adds functions usable in expressions, implemented as plain handlers in an extension.
Details #
A function is a helper people can call inside {{ }} expressions, like the built-in ones. You declare it under adds.functions and implement it with fn(id, handler). The builder is called fn because function is a reserved word.
Once the extension is installed, {{ wordCount(text) }} works in any step field that takes expressions, and in conditions and other expressions.
{
"adds": {
"functions": [{
"id": "word-count", "title": "wordCount(text)",
"params": { "type": "object", "properties": { "text": { "type": "string" } }, "required": ["text"] },
"output": { "type": "integer" }
}]
}
}
import { defineExtension, fn } from '@switchboard/sdk';
export default defineExtension({
functions: [fn('word-count', (p: { text: string }) => p.text.trim().split(/\s+/).length)],
});
The declaration and the code must match. An extension that declares a function it does not implement, or implements one it does not declare, is refused when it loads.
Gotchas #
Keep functions quick and free of side effects. They run in the middle of evaluating an expression, which waits for the answer. A call that takes more than 5 seconds fails with "took too long".
Arguments are not checked for you. Check them in the handler and throw a clear message.
Anything outside the sandbox (network, files, running a program) still needs a permission in the manifest, but a function that waits on the network will feel slow in every expression it is used in. Use an action (actions) for that.
The name people type #
The name is the word before ( in the title: wordCount(text) is called as wordCount. If the title has no (, the name is the id in camelCase, so word-count becomes wordCount. Keep the title as the call reads, so people see how to use it.
What the handler gets and returns #
Input: an object with
args, the list of every argument the expression passed, andtext, the first argument. For a one-argument function,p.textreads best. For more, usep.args.Return: any JSON value. It becomes the value of the expression.
Throw an
Errorto report a problem. The expression fails withname(): your message.
Full example #
The sample below has three functions: one with a single argument (slugify), one with several (clamp) and one that mixes a number and a word (pluralize). You can download it from the Full example section and edit it into your own.