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 · Endpoints/AsyncFunctions.cs · sjs:async-functions.server
View on GitHub
// GET /api/customers/exists?email= — answers emailExists()
app.MapGet("/api/customers/exists", async (string? email, SurveyDb db) =>
{
var normalized = (email ?? "").Trim().ToLowerInvariant();
return new { exists = await db.Customers.AnyAsync(c => c.Email == normalized) };
});
// 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")
app.MapGet("/api/shipping", async (string? postcode, SurveyDb db) =>
{
var code = (postcode ?? "").Replace(" ", "").ToUpperInvariant();
// only a whole German (10115) or UK (SW1A 1AA) postcode gets a price, not anything that starts with a prefix
if (!WholePostcode().IsMatch(code)) return new { price = (decimal?)null };
var rates = await db.ShippingRates.ToListAsync();
var rate = rates.Where(r => code.StartsWith(r.PostcodePrefix, StringComparison.Ordinal)).MaxBy(r => r.PostcodePrefix.Length);
return new { price = rate?.Price };
});