Server functions
Use a server function for anything that needs a secret or an outside service. Export async functions from src/<appId>.server.ts. Each takes (input, ctx) and returns JSON.
Generate one
zp app generate server-function (alias zp app g fn) adds a starter function from a template to src/<appId>.server.ts, creating the file if needed. It refuses a name that isn't camelCase or that the file already exports. In a terminal, it asks for the template; --template picks one.
zp app generate server-function getWarranty --template call-api| Template | What you get |
|---|---|
basic (default) | A function that logs the call with ctx.log and returns { ok: true }. |
call-api | A function that calls an outside API through ctx.fetch with the API_KEY secret, and returns { ok, status, data }. zp also adds api.example.com to allowedDomains. Change the URL, and the host in zuper.app.json, to your API's. In dev mode, put API_KEY=… in .env.local. |
In scripts and coding agents, pass
--defaults(thebasictemplate) or--template. Without a terminal to ask in, zp fails withMissing flags: --template.
Needs
2.0.0-beta. An app on an older SDK may have no--template: runnpm install --save-dev @zuperpro/app-sdk@beta.
A finished function
What a call-api function looks like once it calls your API:
import type { ServerContext } from '@zuperpro/app-sdk/server';
export async function getWarranty(input: { recordId: string }, ctx: ServerContext) {
ctx.log('getWarranty', input.recordId);
const res = await ctx.fetch(`https://api.acme.com/v1/jobs/${input.recordId}`, {
headers: { Authorization: `Bearer ${ctx.secrets.ACME_KEY}` },
});
return (await res.json()) as { expires: string };
}ctx
| Field | Meaning |
|---|---|
appId | Your app id |
company, user | Who is calling. Zuper takes them from the session, never from the browser. |
secrets | Values entered for each company when the app is installed. The browser never sees them. |
fetch(url, init) | Limited to the hosts in allowedDomains |
log(...) | Shows in the zp app dev terminal and in Zuper's function logs |
Call it from your UI
Use a type-only import:
import type { getWarranty } from '../../acme-warranty.server';
const warranty = await server.invoke<typeof getWarranty>('getWarranty', { recordId: record.recordId });Import rules. Server files may import only types, and only from
@zuperpro/app-sdk/server. UI code may import only types from a.serverfile.
Updated about 1 hour ago
