data schema validation
by Matthew Vasallo
JavaScript
/*
User = {}
User.SCHEMA = {
id: string,
name: {
type: string,
required: true,
},
created_at: string,
}
Result:
"INSERT INTO users(name) VALUES('John Smith', `MA`)"
*/
const User = {};
User.SCHEMA = {
columns:{
id: "string",
name: {
type: "string",
required: true,
},
state: {
type: "string",
required: true,
},
created_at: "string",
},
table:"users"
};
const Product = {};
const insertRow = (schema, data) => {
let requiredCols = [];
let valuesToUse = [];
Object.keys(schema.columns).forEach(colName=>{
if(schema.columns[colName].required){
requiredCols.push(colName);
}
});
requiredCols.forEach(colName=>{
if(!data[colName]){
throw `No value provided for column ${colName}`;
}
valuesToUse.push(`'${data[colName]}'`);
});
return `INSERT INTO ${schema.table} VALUES(${valuesToUse.join(", ")})`;
};
console.log(insertRow(User.SCHEMA, {
name: "Matt",
state: "FL"
}));
console.log(insertRow(User.SCHEMA, {
name: "Matt"
}));
// process.stdin.resume();
// process.stdin.setEncoding("ascii");
// var input = "";
// process.stdin.on("data", function (chunk) {
// input += chunk;
// });
// process.stdin.on("end", function () {
// // now we can read/parse input
// });