-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialize-database.js
45 lines (40 loc) · 1.74 KB
/
initialize-database.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Meteor } from 'meteor/meteor';
import { Profiles } from '/imports/api/profile/ProfileCollection';
import { Interests } from '/imports/api/interest/InterestCollection';
import { LFG } from '/imports/api/LFG/LFGCollection';
import { _ } from 'meteor/underscore';
/* global Assets */
/* eslint-disable no-console */
/**
* Returns the definition array associated with collectionName in the restoreJSON structure.
* @param restoreJSON The restore file contents.
* @param collection The collection of interest.
*/
function getDefinitions(restoreJSON, collection) {
return _.find(restoreJSON.collections, obj => obj.name === collection).contents;
}
/**
* Given a collection and the restoreJSON structure, looks up the definitions and invokes define() on them.
* @param collection The collection to be restored.
* @param restoreJSON The structure containing all of the definitions.
*/
function restoreCollection(collection, restoreJSON) {
const definitions = getDefinitions(restoreJSON, collection._collectionName);
console.log(`Defining ${definitions.length} ${collection._collectionName} documents.`);
_.each(definitions, definition => collection.define(definition));
}
Meteor.startup(() => {
/** Only initialize database if it's empty. */
const collectionList = [Interests, Profiles, LFG];
const totalDocuments = _.reduce(collectionList, function reducer(memo, collection) {
return memo + collection.count();
}, 0);
if (totalDocuments === 0) {
const fileName = Meteor.settings.public.initialDatabaseFileName;
console.log(`Restoring database from file ${fileName}.`);
const restoreJSON = JSON.parse(Assets.getText(fileName));
_.each(collectionList, collection => {
restoreCollection(collection, restoreJSON);
});
}
});