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 · routes/async-functions.js · sjs:async-functions.server
View on GitHub
// GET /api/customers/exists?email= — answers emailExists()
app.get("/api/customers/exists", (req, res) => {
const email = typeof req.query.email === "string" ? req.query.email.trim().toLowerCase() : "";
const customer = db(req).prepare("SELECT email FROM customers WHERE email = ?").get(email);
res.json({ exists: customer !== undefined });
});
// 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.get("/api/shipping", (req, res) => {
const postcode = typeof req.query.postcode === "string" ? req.query.postcode.replaceAll(" ", "").toUpperCase() : "";
// only a whole German (10115) or UK (SW1A 1AA) postcode gets a price, not anything that starts with a prefix
if (!/^(\d{5}|[A-Z]{1,2}\d[A-Z\d]?\d[A-Z]{2})$/.test(postcode)) return res.json({ price: null });
const rate = db(req).prepare(`SELECT price FROM shipping_rates WHERE substr(?, 1, length(postcode_prefix)) = postcode_prefix
ORDER BY length(postcode_prefix) DESC LIMIT 1`).get(postcode);
res.json({ price: rate?.price ?? null });
});