-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.js
50 lines (40 loc) · 1.23 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
const chalk = require('chalk');
const bcrypt = require('bcryptjs');
const setupDB = require('./db');
const { ROLE_ADMIN } = require('../constants');
const User = require('../models/user');
const args = process.argv.slice(2);
const email = args[0];
const password = args[1];
const seedDB = async () => {
try {
console.log(`${chalk.blue('✓')} ${chalk.blue('seed db started')}`);
if (!email || !password) throw new Error('missing arguments');
const user = new User({
email,
password,
firstName: 'admin',
lastName: 'admin',
role: ROLE_ADMIN
});
const existingUser = await User.findOne({ email: user.email });
console.log('existingUser', existingUser);
if (existingUser) throw new Error('user collection is seeded!');
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
await user.save();
console.log(`${chalk.green('✓')} ${chalk.green('seed db finished')}`);
} catch (error) {
console.log(
`${chalk.red('x')} ${chalk.red('error while seeding database')}`
);
console.log(error);
return null;
}
};
(async () => {
await setupDB().then(async () => {
await seedDB();
});
})();