JSON definition · shared/definitions/async-functions.json
View on GitHub
{
"title": "Account and delivery details",
"completeText": "Check details",
"completedHtml": "<h3>Your details passed validation.</h3><p>The email is available and delivery is supported.</p>",
"checkErrorsMode": "onValueChanged",
"calculatedValues": [
{
"name": "shipping",
"expression": "shippingCost({postcode})"
}
],
"elements": [
{
"type": "text",
"name": "email",
"title": "Email",
"inputType": "email",
"isRequired": true,
"validators": [
{
"type": "expression",
"expression": "emailExists({email}) = false",
"text": "This email is already registered"
}
]
},
{
"type": "text",
"name": "postcode",
"title": "Postcode",
"isRequired": true,
"description": "Try 10115, 10999, 80331 or SW1A 1AA",
"validators": [
{
"type": "expression",
"expression": "shippingCost({postcode}) > 0",
"text": "We don't deliver to this postcode."
}
]
},
{
"type": "expression",
"name": "shipping_price",
"title": "Shipping",
"visible": false,
"expression": "{shipping}",
"displayStyle": "currency",
"currency": "EUR"
}
]
}
Client · shared/client/async-functions.js · sjs:async-functions.lookup
View on GitHub
// Reuse in-flight and successful lookups, but allow failed requests to be retried
async function lookup(name, key, url, field) {
const run = generation;
const cacheKey = `${name}:${key}`;
if (!cache.has(cacheKey)) {
const pending = fetch(url).then(async response => {
if (!response.ok) throw new Error("Lookup failed");
const value = (await response.json())[field];
if (name === "email" ? typeof value !== "boolean" : value !== null && (!Number.isFinite(value) || value < 0)) throw new Error("Invalid result");
return { ok: true, value };
}).catch(() => ({ ok: false, value: null }));
cache.set(cacheKey, pending);
}
report(name, key, { pending: true }, run);
const pending = cache.get(cacheKey);
const result = await pending;
if (!result.ok && cache.get(cacheKey) === pending) cache.delete(cacheKey);
report(name, key, result, run);
return result.value;
}
Client · shared/client/async-functions.js · sjs:async-functions.client
View on GitHub
// Validate email availability using the backend's customer records
registerFunction({
name: "emailExists",
isAsync: true,
func: async ([email]) => {
const key = normalize("email", email);
if (!key) return false;
return lookup("email", key, `/api/customers/exists?email=${encodeURIComponent(key)}`, "exists");
}
});
// Share one shipping lookup between the calculation and the postcode validator
registerFunction({
name: "shippingCost",
isAsync: true,
func: async ([postcode]) => {
const key = normalize("postcode", postcode);
if (!key) return null;
return lookup("postcode", key, `/api/shipping?postcode=${encodeURIComponent(key)}`, "price");
}
});
Server · app/routes/async_functions.py · sjs:async-functions.server
View on GitHub
# GET /api/customers/exists?email= — answers emailExists()
@router.get("/api/customers/exists")
def customer_exists(db: Db, email: str = "") -> dict[str, bool]:
row = db.execute("SELECT 1 FROM customers WHERE email = ?", (email.strip().lower(),)).fetchone()
return {"exists": row is not None}
# GET /api/shipping?postcode= — answers shippingCost(): the longest matching postcode prefix wins,
# { "price": null } when none matches (the form shows "We don't deliver to this postcode yet")
@router.get("/api/shipping")
def shipping(db: Db, postcode: str = "") -> dict[str, float | None]:
postcode = postcode.replace(" ", "").upper()
if not POSTCODE.match(postcode):
return {"price": None}
rate = db.execute(
"SELECT price FROM shipping_rates WHERE substr(?, 1, length(postcode_prefix)) = postcode_prefix"
" ORDER BY length(postcode_prefix) DESC",
(postcode,),
).fetchone()
return {"price": rate["price"] if rate else None}