Whatever message this page gives is out now! Go check it out!
StructKeyExists(structure, "key")Parameter | Description |
structure | The structure to test. |
key | Key to test. |
<cfscript>
myStruct=StructNew();
myStruct = {a:1,b=2,c=3,d=4,e=5};
ifKeyExists=StructKeyExists(myStruct,"c"); //Returns Yes since key "c" exists
WriteOutput(ifKeyExists & "|");
ifKeyNotExist=StructKeyExists(myStruct,"f"); //Returns No since key "f" does not exist
WriteOutput(ifKeyNotExist);
</cfscript><cfscript>
myStruct = {a:1,b=2,c=3,d=4,e=5};
myKeyExists=myStruct.keyExists("e");
WriteOutput(myKeyExists);
</cfscript><cfscript>
writeOutput("<h2>💳 USE CASE 1: API Response Validation - Payment Processing</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>An e-commerce platform integrates with multiple payment gateways (Stripe, PayPal, Square). Each API returns different response structures, and the application must safely validate response data before processing orders.</p>");
// Simulate different payment gateway responses
stripeResponse = {
"id": "ch_1234567890",
"object": "charge",
"amount": 2500,
"currency": "usd",
"status": "succeeded",
"metadata": {
"order_id": "ORD-2024-001",
"customer_email": "customer@example.com"
}
};
paypalResponse = {
"id": "PAYID-ABC123",
"status": "COMPLETED",
"amount": {
"total": "25.00",
"currency": "USD"
},
"payer": {
"email_address": "customer@example.com"
}
};
squareResponse = {
"payment": {
"id": "sq_payment_123",
"status": "COMPLETED",
"amount_money": {
"amount": 2500,
"currency": "USD"
}
}
};
writeOutput("<h4>🔧 Payment Response Processing Function:</h4>");
function processPaymentResponse(response, gateway) {
result = {
success: false,
transactionId: "",
amount: 0,
currency: "",
status: "",
customerEmail: "",
errors: []
};
try {
// Stripe payment validation
if (gateway == "stripe") {
if (StructKeyExists(response, "id")) {
result.transactionId = response.id;
} else {
arrayAppend(result.errors, "Missing transaction ID in Stripe response");
}
if (StructKeyExists(response, "amount")) {
result.amount = response.amount / 100; // Stripe uses cents
} else {
arrayAppend(result.errors, "Missing amount in Stripe response");
}
if (StructKeyExists(response, "currency")) {
result.currency = uCase(response.currency);
}
if (StructKeyExists(response, "status")) {
result.status = response.status;
result.success = (response.status == "succeeded");
}
// Check for metadata with customer info
if (StructKeyExists(response, "metadata") && StructKeyExists(response.metadata, "customer_email")) {
result.customerEmail = response.metadata.customer_email;
}
}
// PayPal payment validation
else if (gateway == "paypal") {
if (StructKeyExists(response, "id")) {
result.transactionId = response.id;
} else {
arrayAppend(result.errors, "Missing transaction ID in PayPal response");
}
if (StructKeyExists(response, "amount") && StructKeyExists(response.amount, "total")) {
result.amount = val(response.amount.total);
} else {
arrayAppend(result.errors, "Missing amount in PayPal response");
}
if (StructKeyExists(response, "amount") && StructKeyExists(response.amount, "currency")) {
result.currency = response.amount.currency;
}
if (StructKeyExists(response, "status")) {
result.status = response.status;
result.success = (response.status == "COMPLETED");
}
if (StructKeyExists(response, "payer") && StructKeyExists(response.payer, "email_address")) {
result.customerEmail = response.payer.email_address;
}
}
// Square payment validation
else if (gateway == "square") {
if (StructKeyExists(response, "payment")) {
payment = response.payment;
if (StructKeyExists(payment, "id")) {
result.transactionId = payment.id;
} else {
arrayAppend(result.errors, "Missing payment ID in Square response");
}
if (StructKeyExists(payment, "amount_money")) {
if (StructKeyExists(payment.amount_money, "amount")) {
result.amount = payment.amount_money.amount / 100; // Square uses cents
}
if (StructKeyExists(payment.amount_money, "currency")) {
result.currency = payment.amount_money.currency;
}
}
if (StructKeyExists(payment, "status")) {
result.status = payment.status;
result.success = (payment.status == "COMPLETED");
}
} else {
arrayAppend(result.errors, "Missing payment object in Square response");
}
}
} catch (any e) {
arrayAppend(result.errors, "Error processing payment response: " & e.message);
}
return result;
}
// Test payment processing with different gateways
writeOutput("<h4>💰 Payment Processing Results:</h4>");
writeOutput("<table border='1' cellpadding='8' style='width: 100%;'>");
writeOutput("<tr><th>Gateway</th><th>Transaction ID</th><th>Amount</th><th>Status</th><th>Success</th><th>Errors</th></tr>");
gateways = [
{name: "stripe", response: stripeResponse},
{name: "paypal", response: paypalResponse},
{name: "square", response: squareResponse}
];
for (gateway in gateways) {
paymentResult = processPaymentResponse(gateway.response, gateway.name);
errorText = arrayLen(paymentResult.errors) > 0 ? arrayToList(paymentResult.errors, "; ") : "None";
successColor = paymentResult.success ? "green" : "red";
writeOutput("<tr>");
writeOutput("<td><strong>" & uCase(gateway.name) & "</strong></td>");
writeOutput("<td>" & paymentResult.transactionId & "</td>");
writeOutput("<td>$" & numberFormat(paymentResult.amount, "999.99") & " " & paymentResult.currency & "</td>");
writeOutput("<td>" & paymentResult.status & "</td>");
writeOutput("<td style='color: " & successColor & ";'><strong>" & (paymentResult.success ? "✅ YES" : "❌ NO") & "</strong></td>");
writeOutput("<td><small>" & errorText & "</small></td>");
writeOutput("</tr>");
}
writeOutput("</table>");
</cfscript><cfscript>
writeOutput("<h2>👤 USE CASE 2: User Profile Management - Configuration Settings</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>A SaaS application allows users to customize their dashboard, notification preferences, and account settings. Not all users configure every option, so the application must handle missing preferences gracefully with intelligent defaults.</p>");
// Sample user profile data with varying levels of completeness
userProfiles = [
{
userId: 1001,
name: "John Smith",
email: "john@company.com",
preferences: {
theme: "dark",
notifications: {
email: true,
sms: false,
push: true
},
dashboard: {
layout: "grid",
widgets: ["sales", "analytics", "tasks"]
},
timezone: "America/New_York"
}
},
{
userId: 1002,
name: "Sarah Johnson",
email: "sarah@startup.io",
preferences: {
theme: "light",
notifications: {
email: true
}
}
},
{
userId: 1003,
name: "Mike Chen",
email: "mike@techcorp.com"
// No preferences configured yet
}
];
writeOutput("<h4>🔧 User Preferences Processing Function:</h4>");
function processUserPreferences(userProfile) {
// Default preferences structure
defaults = {
theme: "light",
notifications: {
email: true,
sms: false,
push: false
},
dashboard: {
layout: "list",
widgets: ["overview"]
},
timezone: "UTC",
language: "en"
};
processed = {
userId: userProfile.userId,
name: userProfile.name,
email: userProfile.email,
config: {},
customizations: [],
missingSettings: []
};
// Check if user has any preferences configured
if (StructKeyExists(userProfile, "preferences")) {
userPrefs = userProfile.preferences;
// Theme preference
if (StructKeyExists(userPrefs, "theme")) {
processed.config.theme = userPrefs.theme;
arrayAppend(processed.customizations, "Theme: " & userPrefs.theme);
} else {
processed.config.theme = defaults.theme;
arrayAppend(processed.missingSettings, "Theme (using default: " & defaults.theme & ")");
}
// Notification preferences
processed.config.notifications = {};
if (StructKeyExists(userPrefs, "notifications")) {
userNotifs = userPrefs.notifications;
if (StructKeyExists(userNotifs, "email")) {
processed.config.notifications.email = userNotifs.email;
} else {
processed.config.notifications.email = defaults.notifications.email;
arrayAppend(processed.missingSettings, "Email notifications");
}
if (StructKeyExists(userNotifs, "sms")) {
processed.config.notifications.sms = userNotifs.sms;
} else {
processed.config.notifications.sms = defaults.notifications.sms;
arrayAppend(processed.missingSettings, "SMS notifications");
}
if (StructKeyExists(userNotifs, "push")) {
processed.config.notifications.push = userNotifs.push;
} else {
processed.config.notifications.push = defaults.notifications.push;
arrayAppend(processed.missingSettings, "Push notifications");
}
} else {
processed.config.notifications = defaults.notifications;
arrayAppend(processed.missingSettings, "All notification preferences");
}
// Dashboard preferences
processed.config.dashboard = {};
if (StructKeyExists(userPrefs, "dashboard")) {
userDashboard = userPrefs.dashboard;
if (StructKeyExists(userDashboard, "layout")) {
processed.config.dashboard.layout = userDashboard.layout;
arrayAppend(processed.customizations, "Dashboard layout: " & userDashboard.layout);
} else {
processed.config.dashboard.layout = defaults.dashboard.layout;
}
if (StructKeyExists(userDashboard, "widgets")) {
processed.config.dashboard.widgets = userDashboard.widgets;
arrayAppend(processed.customizations, arrayLen(userDashboard.widgets) & " custom widgets");
} else {
processed.config.dashboard.widgets = defaults.dashboard.widgets;
}
} else {
processed.config.dashboard = defaults.dashboard;
arrayAppend(processed.missingSettings, "Dashboard configuration");
}
// Timezone preference
if (StructKeyExists(userPrefs, "timezone")) {
processed.config.timezone = userPrefs.timezone;
arrayAppend(processed.customizations, "Timezone: " & userPrefs.timezone);
} else {
processed.config.timezone = defaults.timezone;
arrayAppend(processed.missingSettings, "Timezone");
}
} else {
// No preferences at all - use all defaults
processed.config = defaults;
arrayAppend(processed.missingSettings, "All preferences (new user)");
}
return processed;
}
// Process all user profiles
writeOutput("<h4>👥 User Profile Processing Results:</h4>");
for (profile in userProfiles) {
userConfig = processUserPreferences(profile);
//writeOutput("<div style='border: 1px solid #ddd; margin: 15px 0; padding: 15px; background-color: #f9f9f9;'>");
writeOutput("<h5>User: " & userConfig.name & " (ID: " & userConfig.userId & ")</h5>");
writeOutput("<table border='1' cellpadding='5' style='width: 100%;'>");
writeOutput("<tr><th>Setting</th><th>Value</th><th>Status</th></tr>");
writeOutput("<tr><td><strong>Theme</strong></td><td>" & userConfig.config.theme & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.customizations, "Theme: " & userConfig.config.theme) > 0 ? "✅ Customized" : "⚙️ Default") & "</td></tr>");
writeOutput("<tr><td><strong>Email Notifications</strong></td><td>" & (userConfig.config.notifications.email ? "Enabled" : "Disabled") & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.missingSettings, "Email notifications") > 0 ? "⚙️ Default" : "✅ Configured") & "</td></tr>");
writeOutput("<tr><td><strong>Dashboard Layout</strong></td><td>" & userConfig.config.dashboard.layout & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.missingSettings, "Dashboard configuration") > 0 ? "⚙️ Default" : "✅ Customized") & "</td></tr>");
writeOutput("<tr><td><strong>Timezone</strong></td><td>" & userConfig.config.timezone & "</td>");
writeOutput("<td>" & (arrayFind(userConfig.customizations, "Timezone: " & userConfig.config.timezone) > 0 ? "✅ Customized" : "⚙️ Default") & "</td></tr>");
writeOutput("</table>");
if (arrayLen(userConfig.customizations) > 0) {
writeOutput("<p><strong>Custom Settings:</strong> " & arrayToList(userConfig.customizations, ", ") & "</p>");
}
if (arrayLen(userConfig.missingSettings) > 0) {
writeOutput("<p><strong>Using Defaults:</strong> <em>" & arrayToList(userConfig.missingSettings, ", ") & "</em></p>");
}
writeOutput("</div>");
}
</cfscript><cfscript>
writeOutput("<h2>📋 USE CASE 3: Form Data Validation - Customer Registration</h2>");
writeOutput("<h3>Business Context:</h3>");
writeOutput("<p>A customer registration system processes forms with required and optional fields. The validation system must handle incomplete submissions gracefully while ensuring required data is present for account creation.</p>");
// Sample form submissions with varying completeness
formSubmissions = [
{
submissionId: "FORM-001",
firstName: "Alice",
lastName: "Johnson",
email: "alice@example.com",
phone: "555-0123",
company: "Tech Solutions Inc",
jobTitle: "Software Engineer",
address: {
street: "123 Main St",
city: "Boston",
state: "MA",
zipCode: "02101"
},
preferences: {
newsletter: true,
productUpdates: false
}
},
{
submissionId: "FORM-002",
firstName: "Bob",
lastName: "Smith",
email: "bob@company.com",
phone: "555-0456"
// Missing optional fields
},
{
submissionId: "FORM-003",
firstName: "Carol",
email: "carol@startup.io"
// Missing last name and phone
}
];
writeOutput("<h4>🔧 Form Validation Function:</h4>");
function validateRegistrationForm(formData) {
validation = {
isValid: false,
requiredFields: ["firstName", "lastName", "email"],
optionalFields: ["phone", "company", "jobTitle", "address", "preferences"],
errors: [],
warnings: [],
processedData: {},
completeness: 0
};
completedFields = 0;
totalFields = arrayLen(validation.requiredFields) + arrayLen(validation.optionalFields);
// Validate required fields
for (field in validation.requiredFields) {
if (StructKeyExists(formData, field) && len(trim(formData[field])) > 0) {
validation.processedData[field] = trim(formData[field]);
completedFields++;
} else {
arrayAppend(validation.errors, "Required field missing: " & field);
}
}
// Process optional fields
for (field in validation.optionalFields) {
if (StructKeyExists(formData, field)) {
if (field == "address" && isStruct(formData[field])) {
// Validate address structure
addressComplete = true;
addressFields = ["street", "city", "state", "zipCode"];
processedAddress = {};
for (addrField in addressFields) {
if (StructKeyExists(formData.address, addrField) && len(trim(formData.address[addrField])) > 0) {
processedAddress[addrField] = trim(formData.address[addrField]);
} else {
addressComplete = false;
}
}
if (addressComplete) {
validation.processedData.address = processedAddress;
completedFields++;
} else {
arrayAppend(validation.warnings, "Incomplete address information");
}
} else if (field == "preferences" && isStruct(formData[field])) {
validation.processedData.preferences = formData[field];
completedFields++;
} else if (len(trim(formData[field])) > 0) {
validation.processedData[field] = trim(formData[field]);
completedFields++;
}
} else {
arrayAppend(validation.warnings, "Optional field not provided: " & field);
}
}
// Email validation
if (StructKeyExists(validation.processedData, "email")) {
if (!isValid("email", validation.processedData.email)) {
arrayAppend(validation.errors, "Invalid email format");
}
}
// Phone validation
if (StructKeyExists(validation.processedData, "phone")) {
phoneClean = reReplace(validation.processedData.phone, "[^0-9]", "", "all");
if (len(phoneClean) < 10) {
arrayAppend(validation.warnings, "Phone number may be incomplete");
}
}
// Overall validation result
validation.isValid = arrayLen(validation.errors) == 0;
validation.completeness = round((completedFields / totalFields) * 100);
return validation;
}
// Process form submissions
writeOutput("<h4>📊 Form Validation Results:</h4>");
for (submission in formSubmissions) {
validationResult = validateRegistrationForm(submission);
//writeOutput("<div style='border: 1px solid #ddd; margin: 15px 0; padding: 15px;'>");
writeOutput("<h5>Form Submission: " & submission.submissionId & "</h5>");
statusColor = validationResult.isValid ? "green" : "red";
completenessColor = validationResult.completeness >= 80 ? "green" : (validationResult.completeness >= 60 ? "orange" : "red");
writeOutput("<p><strong>Validation Status:</strong> <span style='color: " & statusColor & ";'>" & (validationResult.isValid ? "✅ VALID" : "❌ INVALID") & "</span></p>");
writeOutput("<p><strong>Form Completeness:</strong> <span style='color: " & completenessColor & ";'>" & validationResult.completeness & "%</span></p>");
if (arrayLen(validationResult.errors) > 0) {
writeOutput("<p><strong style='color: red;'>Errors:</strong></p>");
writeOutput("<ul>");
for (error in validationResult.errors) {
writeOutput("<li style='color: red;'>" & error & "</li>");
}
writeOutput("</ul>");
}
if (arrayLen(validationResult.warnings) > 0) {
writeOutput("<p><strong style='color: orange;'>Warnings:</strong></p>");
writeOutput("<ul>");
for (warning in validationResult.warnings) {
writeOutput("<li style='color: orange;'>" & warning & "</li>");
}
writeOutput("</ul>");
}
writeOutput("<p><strong>Processed Fields:</strong></p>");
writeOutput("<table border='1' cellpadding='5'>");
writeOutput("<tr><th>Field</th><th>Value</th><th>Type</th></tr>");
for (field in validationResult.processedData) {
value = validationResult.processedData[field];
fieldType = arrayFind(validationResult.requiredFields, field) > 0 ? "Required" : "Optional";
if (isStruct(value)) {
displayValue = "Structure with " & structCount(value) & " properties";
} else {
displayValue = len(value) > 30 ? left(value, 30) & "..." : value;
}
writeOutput("<tr>");
writeOutput("<td><strong>" & field & "</strong></td>");
writeOutput("<td>" & displayValue & "</td>");
writeOutput("<td>" & fieldType & "</td>");
writeOutput("</tr>");
}
writeOutput("</table>");
writeOutput("</div>");
}
</cfscript>