Conditional operations
FQL doesn’t have a ternary (conditional) operator. You can get the same result
using an if … else
statement. For
example, to perform an upsert:
// Customer email to look up
let email = "alice.appleseed@example.com"
// Customer data to upsert
let data = {
name: "Alice Appleseed",
email: "alice.appleseed@example.com",
address: {
street: "87856 Mendota Court",
city: "Washington",
state: "DC",
postalCode: "20220",
country: "US"
}
}
// Try to find the existing customer by email.
// If the customer doesn't exist, returns `null`.
let customer = Customer.byEmail(email).first()
// Create or update the customer based on existence.
// If customer is null, create a new customer.
// Otherwise, update the existing one.
if (customer == null) {
Customer.create(data)
} else {
customer!.update(data)
}
Null checking
If you’re checking for a null value, you can use the
null coalescing (??
)
operator to return a default value when an expression is null
. For example:
// Try to find the existing customer by email.
// If the customer doesn't exist, return `null`.
let customer = Customer.byEmail("carol.clark@example.com")?.first()
// Use the null coalescing (??) operator to return the customer's
// cart. If the customer or their cart is `null`, return `"Not found"`.
// In this case, the customer's cart is `null`.
customer?.cart ?? "Not found" // returns "Not found"