Step 1 - Connect to Server

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
// db.js
const Sequelize = require('sequelize')
const _ = require('lodash')
const Faker = require('faker')

const Conn = new Sequelize(
'test',
'postgres',
'postgres',
{
dialect: 'postgres',
host: 'localhost',
}
)

const Person = Conn.define('person', {
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail: true,
}
}
})

const Post = Conn.define('post', {
title: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.STRING,
allowNull: false,
},
})

// Relationships
Person.hasMany(Post)
Post.belongsTo(Person)

Conn.sync({
force: true,
}).then( () => {
_.times(10, () => {
return Person.create({
firstName: Faker.name.firstName(),
lastName: Faker.name.lastName(),
email: Faker.internet.email(),
}).then(person => {
return person.createPost({
title: `Sample title by ${person.firstName}`,
content: 'This is a sample article',
})
})
})
})

module.exports = Conn

Step 2 - Build Schema

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
// schema.js
const Sequelize = require('sequelize')
const _ = require('lodash')
const Faker = require('faker')

const Conn = new Sequelize(
'test',
'postgres',
'postgres',
{
dialect: 'postgres',
host: 'localhost',
}
)

const Person = Conn.define('person', {
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
validate: {
isEmail: true,
}
}
})

const Post = Conn.define('post', {
title: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.STRING,
allowNull: false,
},
})

// Relationships
Person.hasMany(Post)
Post.belongsTo(Person)

Conn.sync({
force: true,
}).then( () => {
_.times(10, () => {
return Person.create({
firstName: Faker.name.firstName(),
lastName: Faker.name.lastName(),
email: Faker.internet.email(),
}).then(person => {
return person.createPost({
title: `Sample title by ${person.firstName}`,
content: 'This is a sample article',
})
})
})
})

module.exports = Conn

Step 3 - Add GraphQL to Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// server.js
const Express = require('express')
const GraphHTTP = require('express-graphql')
const Schema = require('./schema')

// Config
const APP_PORT = 3000

const app = Express()
app.use('/graphql', GraphHTTP({
schema: Schema,
pretty: true,
graphiql: true,
}))

app.listen(APP_PORT, () => {
console.log('Server listening at ' + APP_PORT)
})