Goal:
Using JavaScript promises, on load(), if the database is not already populated, seed it with data, then display the data with getWidgets(), otherwise, if the db is already seeded just getWidgets().
The code:
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));
})
}
What would be the proper way to handle these three methods with promises when in load() ...
- seed database if not already populated
- add the records to session
- display session objects
Thanks