Skip to main content

Functions

A Function in an Andera Worker is a unit of business logic that can be called via the /task endpoint. Functions are defined in the src/functions/ directory and are auto-discovered at startup.

Structure of a Function

A function is defined using defineFunction from @andera-top/worker-core. Each function specifies:

  • params: The input parameters and their types
  • config: Optional configuration (timeout, retries, streaming, etc.)
  • handler: The async function that implements the logic

Parameter Schema Options

Each parameter in params can have the following options:

OptionTypeDescriptionDefault
typestringParameter type: string, number, boolean, object, array'string'
requiredbooleanWhether the parameter is requiredtrue
defaultanyDefault value if not provided'World'
enumany[]Allowed values (for enums)["foo", "bar"]
patternstringRegex pattern (for strings)'^\w+$'
minnumberMinimum value/length (number, string, array)1
maxnumberMaximum value/length (number, string, array)10
tip

Use enum, pattern, min, and max to validate and restrict input values.

Function Config Options

The config object can have the following options:

OptionTypeDescriptionDefault
timeoutnumberTimeout in ms for the function5000
maxRetriesnumberNumber of times to retry on failure1
supportsStreamingbooleanWhether the function supports streaming modefalse
logResultbooleanWhether to log the function result (default: true). This avoids polluting logs with heavy data or secrets.false

Example

import { defineFunction } from '@andera-top/worker-core'
import { log } from '@andera-top/worker-core/dist/utils/logger'

export const hello = defineFunction({
params: {
name: { type: 'string', required: false, default: 'World' }
},
config: {
timeout: 5000,
maxRetries: 0,
supportsStreaming: true
},
handler: async (params, context) => {
log('[HELLO]', `Hello function called for ${params.name}`)
if (context?.stream) {
context.stream(`Hello ${params.name}!`)
return { streaming: true }
}
return { message: `Hello ${params.name}!` }
}
})

Logging in Functions

You can use the logging utilities to trace function calls, warnings, or errors (see Logging):

import { log, warn, error } from '@andera-top/worker-core/dist/utils/logger'

log('[MYFUNC]', 'Function called')
warn('[MYFUNC]', 'Something might be wrong')
error('[MYFUNC]', 'Something went wrong')

Creating a New Function

  1. Create a new file in src/functions/, e.g. myFunction.ts.
  2. Export your function using defineFunction as shown above.
  3. The function will be auto-registered at startup.

Testing a Function

You can test your function by sending a POST request to the /task endpoint of your Worker:

curl -X POST http://localhost:3000/task \
-H 'Authorization: <AUTH_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"function": "myFunction",
"input": { "name": "Function" },
"contract": 1,
"mode": "sync"
}'

The response will contain the result of your function.