-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
91 lines (76 loc) · 1.68 KB
/
db.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
import Sequelize from 'sequelize';
import _ from 'lodash';
import Faker from 'faker';
const DB_NAME = 'relay';
const DB_USR_NAME = 'postgres';
const DB_PWD = 'postgres';
const DB_DIALECT = 'postgres';
// Define a connection
const Connection = new Sequelize(
DB_NAME,
DB_USR_NAME,
DB_PWD,
{
dialect: DB_DIALECT,
host: 'localhost',
operatorsAliases: false
},
);
// Define a table: people
const Person = Connection.define('person', {
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail: true,
},
},
});
// Define a table: posts
const Post = Connection.define('post', {
title: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.STRING,
allowNull: false,
}
});
// Set table relationships
Person.hasMany(Post);
Post.belongsTo(Person);
// Sync db
// If force then dont create tables if already exist
Connection.sync({ force: true })
.then((() => {
console.info(`Connected to db: ${DB_NAME}`);
// Create 10 fake users
_.times(10, () => {
return Person.create({
firstName: Faker.name.firstName(),
lastName: Faker.name.lastName(),
email: Faker.internet.email(),
})
.then(person => { // Create a fake post
return person.createPost({
title: `Sample title by ${person.firstName}`,
content: `This is a sample article`,
});
})
;
});
}))
.catch(() => {
console.error(`Failed to connect to db: ${DB_NAME}`);
})
;
export default Connection;