目标:
使用 JavaScript 承诺,在 load() 上,如果数据库尚未填充,则使用数据为其播种,然后使用 getWidgets() 显示数据,否则,如果数据库已经播种,则只需 getWidgets()。
编码:
const initialWidgets = [
{id: 1, color: 'Red', sprocketCount: 7, owner: 'John'},
{id: 2, color: 'Taupe', sprocketCount: 1, owner: 'George'},
{id: 3, color: 'Green', sprocketCount: 8, owner: 'Ringo'},
{id: 4, color: 'Blue', sprocketCount: 2, owner: 'Paul'}
];
require('./model');
const Widget = require('mongoose').model('WidgetModel');
function seedWidgets() {
let results = [];
Widget.find({}, function (err, collection) {
if (err) { throw err;}
if (collection.length === 0) {
initialWidgets.map(widget => {
Widget.create(widget);
});
}
})
}
export function getWidgets(req) {
let widgets = req.session.widgets;
if (!widgets) {
/// ?? seed database
/// ?? add new records to session
}
return widgets;
}
export default function load(req) {
return new Promise((resolve, reject) => {
resolve(getWidgets(req));
})
}
在 load() 中处理这三种方法的正确方法是什么?
- 种子数据库(如果尚未填充)
- 将记录添加到会话
- 显示会话对象
谢谢