Skip to content

Instantly share code, notes, and snippets.

@nf3
Created April 13, 2023 23:38
Show Gist options
  • Save nf3/9f74382c44b1758127f2236c9193520b to your computer and use it in GitHub Desktop.
Save nf3/9f74382c44b1758127f2236c9193520b to your computer and use it in GitHub Desktop.
function attachFormSubmit(form, baseid, tableToGet, preventDefault=true){
form.addEventListener('submit', (event) => {
if (preventDefault) {
console.log("preventDefault", preventDefault);
event.preventDefault();
event.stopPropagation();
}
if (typeof form.validationFunction === 'function' && !form.validationFunction(event)) {
if (typeof form.cb === 'function') {
form.cb({"error":"invalid"});
} else {
return {"error":"invalid"};
}
} else {
let formData = new FormData(form);
let object = {};
console.log("formData");
console.log(formData);
formData.forEach((value, key) => {
console.log("value");
console.log(value);
console.log("key");
console.log(key);
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
let record = object;
console.log("record");
console.log(record);
if (typeof form.cb === 'function') {
createRecord(record, baseid, tableToGet, form.cb);
} else {
createRecord(record, baseid, tableToGet);
}
}
})
}
function createRecord(record, baseid, tableToGet, cb){
const tableProxyURL = window.vv_process.env.VV_BASE_URL + '/v0/' + baseid + '/' + tableToGet;
const createSingle = JSON.stringify({
fields: {...record
}
});
fetch(tableProxyURL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: createSingle,
credentials: 'include'
})
.then(res=>{
return res.json();
})
.then(res=>{
typeof cb === 'function' && cb(res);
}).catch(err=>console.log(err))
}
const formList = document.querySelectorAll(".auth-form");
if (formList && formList.length > 0 ) {
formList.forEach(node => {
const authTable = node.getAttribute("data-auth-table");
const authBaseid = node.getAttribute("data-auth-baseid");
const authPreventDefault = node.getAttribute("data-auth-preventDefault");
if (user && authTable && authBaseid) {
attachFormSubmit(node, authBaseid, authTable, authPreventDefault);
//The unauthenticated case
} else {
throw new Error("user is not authenticated.");
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment