我有一个传递给函数的对象,并希望使用这些值保存一个 DB 条目,并可以选择具有一些默认值。
实际上...
我在猫鼬中有这样的模式:
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);
要在这张桌子上写东西,我有类似的东西:
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();
}
这绝对是糟糕的代码。没有重复的更好的写作方式是什么?