-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathseed.js
266 lines (247 loc) · 7.47 KB
/
seed.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/* eslint-disable node/no-unsupported-features/es-syntax */
const mongoose = require('mongoose');
const faker = require('faker');
const chalk = require('chalk');
const dotenv = require('dotenv');
const User = require('./server/models/User');
const Teacher = require('./server/models/Teacher');
const Student = require('./server/models/Student');
const Lesson = require('./server/models/Lesson');
const Grade = require('./server/models/Grade');
// Make all variables from our .env file available in our process
dotenv.config({ path: '.env.example' });
// connect db
const connectDB = async cb => {
try {
// MongoDB setup.
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
await mongoose.connect(process.env.MONGODB_URI);
/* Drop the DB */
mongoose.connection.db.dropDatabase();
} catch (e) {
console.error(e.message);
console.log(
'%s MongoDB connection error. Please make sure MongoDB is running.',
chalk.red('✗')
);
// Exit process with failure
process.exit(1);
}
cb();
};
const createUsers = role => {
console.log(chalk.green('Creating'), role);
return new Promise((resolve, reject) => {
const users = [];
for (let i = 0; i < 5; i += 1) {
const firstName = faker.name.firstName();
const lastName = faker.name.lastName();
const email = faker.internet.email(firstName, lastName);
const roleProps =
role === 'student'
? { _student: new mongoose.Types.ObjectId() }
: { _teacher: new mongoose.Types.ObjectId() };
const newUser = {
_id: new mongoose.Types.ObjectId(),
name: `${firstName} ${lastName}`,
email,
password: 'MySecretPass123',
role,
...roleProps
};
users.push(newUser);
}
if (users.length) {
resolve(users);
} else {
reject(new Error('Reject: Users not created'));
}
});
// return users;
};
const generateIndexes = (limit, range) => {
const result = [];
while (result.length < limit) {
const random = Math.floor(Math.random() * range);
if (result.indexOf(random) === -1) result.push(random);
}
return result;
};
const generateStudentsId = students => {
const studentsId = [];
const limit = students.length > 25 ? 25 : students.length;
const indexes = generateIndexes(limit, students.length);
indexes.forEach(i => studentsId.push(students[i]._student));
return studentsId;
};
const createLessons = (teachers, students) => {
console.log(chalk.green('Creating'), 'Lessons');
return new Promise((resolve, reject) => {
const lessons = [];
teachers.forEach(teacher => {
const studentsId = generateStudentsId(students);
const title = faker.name.title();
const description = faker.lorem.paragraph();
const newLesson = {
_id: new mongoose.Types.ObjectId(),
title,
description,
_teacher: teacher._teacher,
_students: studentsId
};
lessons.push(newLesson);
});
if (lessons.length) {
resolve(lessons);
} else {
reject(new Error('Reject: Lessons not created'));
}
});
};
const createGrades = lessons => {
console.log(chalk.green('Creating'), 'Grades');
return new Promise((resolve, reject) => {
const grades = [];
lessons.forEach(lesson => {
const { _students, _teacher } = lesson;
const newGrade = {
_id: new mongoose.Types.ObjectId(),
grade: Math.floor(Math.random() * 10) + 1,
_lesson: lesson._id,
_student: _students[Math.floor(Math.random() * _students.length)]._id,
_teacher
};
grades.push(newGrade);
});
if (grades.length) {
resolve(grades);
} else {
reject(new Error('Reject: Grades not created'));
}
});
};
const saveAdmin = async () => {
console.log(chalk.green('Saving'), 'Admin');
const admin = await new User({
name: 'super admin',
email: '[email protected]',
password: 'MySecretPass123',
role: 'admin'
});
await admin.save();
};
async function saveTeachers(teachers, lessons, grades) {
console.log(chalk.green('Saving'), 'teachers');
const teachersClone = teachers.map(teacher => ({ ...teacher, _lesson: '', _grades: [] }));
lessons.forEach(lesson => {
if (lesson._teacher) {
const index = teachers.findIndex(teacher => teacher._teacher === lesson._teacher);
teachersClone[index] = { ...teachersClone[index], _lesson: lesson._id };
}
});
grades.forEach(grade => {
if (grade._teacher) {
const index = teachers.findIndex(teacher => teacher._teacher === grade._teacher);
teachersClone[index] = {
...teachersClone[index],
_grades: [grade._id]
};
}
});
teachersClone.forEach(async teacher => {
const { _lesson, _grades, ...rest } = teacher;
if (!teacher._teacher) return;
try {
const newUser = await new User({ ...rest });
const newTeacher = await new Teacher({
_id: teacher._teacher,
_user: newUser._id,
_lesson,
_grades
});
await newUser.save();
await newTeacher.save();
} catch (error) {
console.log(error);
}
});
}
async function saveStudents(students, lessonsArr, gradesArr) {
console.log(chalk.green('Saving'), 'student');
const studentsClone = students.map(student => ({ ...student, _lessons: [], _grades: [] }));
lessonsArr.forEach(lesson => {
if (lesson._students) {
lesson._students.forEach(stu => {
const index = students.findIndex(student => student._student === stu);
studentsClone[index]._lessons.push(lesson._id);
});
}
});
gradesArr.forEach(grade => {
if (grade._student) {
const studentIndex = students.findIndex(student => student._student === grade._student);
studentsClone[studentIndex]._grades.push(grade._id);
}
});
studentsClone.forEach(async student => {
const { _lessons, _grades, ...rest } = student;
if (!student._student) return;
try {
const newUser = await new User({ ...rest });
const newStudent = await new Student({
_id: student._student,
_user: newUser._id,
_lessons,
_grades
});
await newUser.save();
await newStudent.save();
} catch (error) {
console.log(error);
}
});
}
const saveLessons = async lessons => {
console.log(chalk.green('Saving'), 'Lessons');
lessons.forEach(async lesson => {
try {
const newLesson = await new Lesson(lesson);
await newLesson.save();
} catch (error) {
console.log(error);
}
});
};
const saveGrades = async grades => {
console.log(chalk.green('Saving'), 'Grades');
grades.forEach(async grade => {
try {
const newGrade = await new Grade(grade);
await newGrade.save();
} catch (error) {
console.log(error);
}
});
};
const seed = async () => {
console.log(chalk.green('seed'), 'just started');
const teachers = await createUsers('teacher');
const students = await createUsers('student');
const lessons = await createLessons(teachers, students);
const grades = await createGrades(lessons, students);
setTimeout(() => {
saveTeachers(teachers, lessons, grades);
saveStudents(students, lessons, grades);
saveLessons(lessons);
saveGrades(grades);
}, 1000);
setTimeout(() => saveAdmin(), 3000);
setTimeout(() => {
console.log(chalk.green('seed'), 'just ended');
process.exit();
}, 10000);
};
connectDB(seed);