I have an object passed to a function, and want to save a DB entry with those values, with the option to have some defaults.
In practical terms...
I have a schema like this in Mongoose:
var Log = new Schema({
workspaceId : { type: String, index: true },
workspaceName : { type: String, index: true },
loginSession : { type: String, index: true },
loginToken : { type: String, index: true },
logLevel : { type: Number, enum:[0,1] },
errorName : { type: String, index: true },
message : { type: String, index: true },
reqInfo : { type: String },
data : { type: String },
loggedOn : { type: Date, index: true },
});
mongoose.model('Log', Log);
To write things on this table, I have something like:
exports.Logger = function(logEntry){
var Log = mongoose.model("Log"),
req = logEntry.req;
log = new Log();
// Sorts out log.reqInfo
if ( logEntry.req){
log.reqInfo = JSON.stringify({
info : req.info,
headers: req.headers,
method : req.method,
body :req.body,
route :req.route,
params: req.params
});
} else {
logEntry.reqInfo = {};
}
// Sorts out all of the other fields with sane defaults.
// FIXME: improve this code, it's grown into something ugly and repetitive
log.workspaceId = logEntry.workspaceId ? logEntryworkspaceId. : '';
log.workspaceName = logEntry.workspaceName ? logEntry.workspaceName : '';
log.loginSession = logEntry.loginSession ? logEntry.loginSession : '';
log.loginToken = logEntry.loginToken ? logEntry.loginToken : '';
log.logLevel = logEntry.logLevel ? logEntry.logLevel : 0;
log.errorName = logEntry.errorName ? logEntry.errorName : '';
log.message = logEntry.message ? logEntry.message : '';
log.data = logEntry.data ? logEntry.data : {};
// Sorts out log.loggedOn
log.loggedOn = new Date();
log.save();
}
This is absolutely awful code. What's a better way of writing it, without the repetition?
I dont understand your code. So, if a value isn't set you want it to be set to empty string ''
?
If you want defaults, easiest way is to just define them in your schema.
var Log = new Schema({
workspaceId : { type: String, index: true, default: 'your default here' },
//...
loggedOn : { type: Date, index: true, default: Date.now }
});
From docs
Something like this might be a bit more elegant:
Create a dictionary containing the default values
defaults = {
workspaceName: 'foo',
loginSession: 'bar',
loginToken: 'baz'
};
console.log(defaults)
Given some values
values = {
workspaceName: 'WNAME1',
loginSession: 'LS1',
somethingElse: 'qux'
};
console.log(values)
If values doesn't contain an entry for any of the specified defaults, add the default value to values
for(i in defaults){
if(!values[i]){
values[i] = defaults[i];
}
}
console.log(values)