class FormCache {
constructor() {
this.cache = {}; // Store form data and results
this.logLevel = 'verbose'; // Set log level (e.g., 'debug', 'info', 'warn', 'error', 'verbose')
}
_log(message) {
console.log(`[${this.logLevel}] ${message}`);
}
/**
* Caches the result of a web form submission.
* @param {string} formId - Unique identifier for the form.
* @param {object} formData - The form data.
* @param {function} submitForm - Function to submit the form (returns a promise).
* @returns {Promise<any>} - A promise that resolves with the cached result, or rejects if not cached.
*/
cacheFormResult(formId, formData, submitForm) {
this._log(`Caching form ${formId} with data: ${JSON.stringify(formData)}`);
const cacheKey = `${formId}-${JSON.stringify(formData)}`;
if (this.cache[cacheKey]) {
this._log(`Retrieving from cache for form ${formId}`);
return this.cache[cacheKey];
}
return submitForm()
.then(result => {
this.cache[cacheKey] = result; // Store the result in the cache
this._log(`Form ${formId} cached successfully.`);
return result;
})
.catch(error => {
this._log(`Error submitting form ${formId}:`, error);
throw error; // Re-throw the error
});
}
/**
* Retrieves a form result from the cache.
* @param {string} formId - Unique identifier for the form.
* @param {object} formData - The form data.
* @returns {any} - The cached result, or undefined if not found.
*/
getFormResult(formId, formData) {
const cacheKey = `${formId}-${JSON.stringify(formData)}`;
if (this.cache[cacheKey]) {
this._log(`Retrieving from cache for form ${formId}`);
return this.cache[cacheKey];
} else {
this._log(`Form ${formId} not found in cache.`);
return undefined;
}
}
/**
* Clears the cache.
*/
clearCache() {
this._log("Clearing the cache.");
this.cache = {};
}
}
// Example Usage (replace with your actual form submission logic)
// const formCache = new FormCache();
// async function submitMyForm(formData) {
// // Simulate a form submission with a promise
// return new Promise(resolve => {
// setTimeout(() => {
// resolve(`Result for form with data: ${JSON.stringify(formData)}`);
// }, 500);
// });
// }
// async function main() {
// const formId = "my-form";
// const formData = { name: "John Doe", age: 30 };
// // First submission - submit the form
// const result1 = await formCache.cacheFormResult(formId, formData, submitMyForm);
// console.log("First result:", result1);
// // Second submission with the same data - retrieve from cache
// const result2 = formCache.getFormResult(formId, formData);
// console.log("Second result (from cache):", result2);
// //Try getting a non-cached form
// const result3 = formCache.getFormResult('different-form', {a:1});
// console.log("Third result (not cached):", result3);
// //Clear the cache
// formCache.clearCache();
// }
// main();
Add your comment