Database Oluştur

İlk olarak bir database ve kullanıcı oluştur.

1
2
3
4
5
sudo -u postgres -i
createdb database_ismi
psql database_ismi
CREATE USER user-name WITH PASSWORD "user-password"
GRANT ALL PRIVILEGES ON DATABASE "database_ismi" to username

Knex

Data senkronizasyonu ve migrasyonu için knex adlı paketten yararlanabilirsin. Proje rootta knex init ile knexfile.js oluştur. Konfiguasyon bilgilerini knexfile.js‘e gir.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// ./knexfile.js
module.exports = {
development: {
client: 'postgresql',
connection: {
database: 'database_ismi',
user: 'database_kullanici',
password: 'db_sifre'
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
},
// ...

PostgreSQL Client

Node için postgres client’ını yükle.

1
npm install --save pg

Tablo için migration dosyası oluştur.

1
knex migrate:make tablo_ismi

Tablo Oluştur

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ./migrations/20161010xxxxxx_tablo-ismi.js
// tablo oluştur
exports.up = function(knex, Promise) {
return knex.schema.createTable('tablo_ismi', function(table) {
table.increments(); // increment ederek id oluştur.
table.string('username').notNullable().unique();
table.string('email').notNullable().unique();
table.string('timezone').notNullable();
table.string('password_digest').notNullable();
table.timestamps(); // createAt ve updatedAt oluştur.
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('tablo_ismi');
};

knex migrate:latest ile tabloyu migrate et.

ORM

bookshelf paketini ORM olark kullanabilirsin, knex ile çalışıyor. Bookshelf instance’ı oluştur.

1
2
3
4
5
6
7
8
// server/bookshelf.js
import knex from 'knex';
import bookshelf from 'bookshelf';
import knexConfig from '../knexfile';
export default bookshelf(knex(knexConfig.development));

Örnek

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
// server/models/user.js
import bookshelf from '../bookshelf'; // Our initialized instance of bookshelf
export default bookshelf.Model.extend({
tableName: 'users'
});
// server/routes/users.js
import express from 'express';
import commonValidations from '../shared/validations/signup';
import bcrypt from 'bcrypt';
import isEmpty from 'lodash/isEmpty';
import User from '../models/user';
let router = express.Router();
function validateInput(data, otherValidations) {
let { errors } = otherValidations(data);
// uniqueness check promise
return User.query({
where: { email: data.email },
orWhere: { username: data.username }
}).fetch().then(user => {
if (user) {
if (user.get('username') === data.username) {
errors.username = 'There is user with such username';
}
if (user.get('email') === data.email) {
errors.email = 'There is user with such email';
}
}
return {
errors,
isValid: isEmpty(errors)
};
})
}
// /users route
router.post('/', (req, res) => {
validateInput(req.body, commonValidations).then(({ errors, isValid }) => {
if (isValid) {
const { username, password, timezone, email } = req.body;
const password_digest = bcrypt.hashSync(password, 10);
User.forge({
username, timezone, email, password_digest
}, {
hasTimestamps: true } //options
).save() //returns a promise
.then(user => res.json({ success: true }))
.catch(err => res.status(500).json({ error: err }));
} else {
res.status(400).json(errors);
}
})
});
router.get('/:identifier', (req, res) => {
User.query({
select: ['username', 'email'],
where: { email: req.params.identifier },
orWhere: { username: req.params.identifier }
}).fetch().then(user => {
res.json({ user });
});
});
export default router;

Örnek Rem Zolotykh‘ın Youtube’da paylaştığı Redux - React tutorial’ından. Repo