-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
103 lines (93 loc) · 2.37 KB
/
server.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
const express = require('express')
var cors = require('cors')
const bodyParser = require('body-parser')
const bycrypt = require('bcryptjs')
const knex = require('knex')
const db = knex({
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : 'root',
database : 'smartbrain'
}
});
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.json("Welcome to smartbrain app api's")
})
app.post('/signin', (req, res) => {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json('incorrect form submission')
}
db.select('email', 'hash').from('login')
.where({ email })
.then(data => {
const isValid = bycrypt.compareSync(password, data[0].hash)
if(isValid) {
return db.select('*').from('users')
.where({email})
.then(user => res.json(user[0]))
.catch(err => res.status(400).json('unable to get user'))
}
else {
res.json('Wrong password')
}
})
.catch(err => res.status(400).json('wrong credientials'))
})
app.post('/register', (req, res) => {
const { email, name, password } = req.body
if (!email || !password || !name) {
return res.status(400).json('incorrect form submission')
}
const hash = bycrypt.hashSync(password)
db.transaction(trx => {
trx.insert({
hash,
email,
})
.into('login')
.returning('email')
.then(loginEmail => {
return trx('users')
.returning('*')
.insert({
email: loginEmail[0],
name,
joined: new Date(),
entries: 0
})
.then(user => res.json(user[0]))
})
.then(trx.commit)
.catch(trx.rollback)
})
.catch(err => res.status(400).json('unable to register'))
})
app.get('/profile/:id', (req, res) => {
const { id } = req.params
return db.select('*').from('users').where({ id })
.then(user => {
if(user.length){
res.json(user[0])
} else {
res.status(400).json('no user found')
}
})
})
app.put('/image', (req, res) => {
const { id } = req.body
return db('users')
.where({id})
.increment('entries', 1)
.returning('entries')
.then(entries =>res.json(entries[0]))
.catch(err => res.status(400).json("unable to get entries"))
})
app.listen(4000, () => {
console.log('app is running on port 4000')
})