-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (57 loc) · 1.93 KB
/
index.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
(async function () {
require('dotenv').config()
const express = require('express')
const http = require('http')
const hbs = require('express-handlebars')
const path = require('path')
const {Client} = require('pg')
const app = express()
// configure db and connect
const client = new Client({
connectionString: process.env.DATABASE_URL
})
await client.connect()
// setup express
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'main',
layoutsDir: __dirname + '/views/layouts/',
partialsDir: __dirname + '/views/partials/'
}));
app.set('view engine', 'hbs');
// middleware
app.use(express.static(path.join(__dirname, '/public')))
app.use(express.urlencoded({
extended: true
}))
// routes
app.get('/signup', function (req, res, next) {
res.render('signup', {layout: 'index', fpjsPublicApiKey: process.env.FPJS_PUBLIC_API_KEY})
})
// signup form submission
app.post('/signup', async function signup(req, res, next) {
const {email, visitorId} = req.body
try {
if (!email) {
throw new Error('email is required')
}
const hasVisitorId = (await client.query('select * from users where visitor_id = $1', [visitorId])).rows.length > 0
if (hasVisitorId) {
throw new Error('Looks like you already have an account, please sign in')
}
const result = await client.query('insert into users(email, visitor_id) values($1, $2) returning *', [email, visitorId])
console.log(`${result.rows[0].email} added to the db`)
res.render('signup_success', {layout: 'index'})
} catch (e) {
console.error(e)
let message = e.message
if (e.code === '23505') {
message = 'User with this email already exists'
}
res.render('signup', {layout: 'index', fpjsToken: process.env.FPJS_TOKEN, error: message, email})
}
})
// create server
const server = http.createServer(app)
server.listen('3002')
}());