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 · src/main/java/io/surveyjs/examples/AsyncFunctionsController.java · sjs:async-functions.server
View on GitHub
// GET /api/customers/exists?email= — answers emailExists()
@GetMapping("/api/customers/exists")
public Map<String, Boolean> customerExists(@RequestParam(defaultValue = "") String email) {
boolean exists = jdbc.sql("SELECT COUNT(*) FROM customers WHERE email = ?")
.param(email.strip().toLowerCase(Locale.ROOT)).query(Integer.class).single() > 0;
return Map.of("exists", exists);
}
// 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")
@GetMapping("/api/shipping")
public Price shipping(@RequestParam(defaultValue = "") String postcode) {
String code = postcode.replace(" ", "").toUpperCase(Locale.ROOT);
if (!POSTCODE.matcher(code).matches()) {
return new Price(null);
}
return new Price(jdbc.sql("SELECT price FROM shipping_rates WHERE ? LIKE postcode_prefix || '%'"
+ " ORDER BY LENGTH(postcode_prefix) DESC LIMIT 1")
.param(code).query(Double.class).optional().orElse(null));
}