-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
185 lines (157 loc) · 4.06 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// check for environment variables
if (!process.env.CLOUDANT_URL || !process.env.CLOUDANT_APIKEY) {
console.error('Please create CLOUDANT_URL & CLOUDANT_APIKEY environment variables before running. See README for details.')
process.exit(1)
}
const express = require('express')
const bodyParser = require('body-parser')
const { CloudantV1 } = require('@ibm-cloud/cloudant')
const client = CloudantV1.newInstance()
const USERDB = 'users'
const STORYDB = 'stories'
// constants
const PORT = 8080
const HOST = '0.0.0.0'
// the express app
const app = express()
app.use(express.static('public'))
app.use(bodyParser.json())
// POST /register endpoint for registering users
app.post('/api/register', async (req, res) => {
console.log('POST /api/register')
const user = req.body
const response = await client.postDocument({
db: USERDB,
document: user
})
res.send(response)
})
app.post('/api/stories/addstoryboard', async (req, res) => {
console.log("POST /api/stories/addstoryboard");
const storyboard = req.body
const response = await client.postDocument({
db: STORYDB,
document: storyboard
})
})
// GET /users endpoint
app.get('/api/users', async (req, res) => {
console.log('GET /api/users')
// get users in reverse chrono order, limit 50
const response = await client.postFind({
db: USERDB,
selector: {},
sort: [{
dateCreated: 'desc'
}],
limit: 50
})
res.send({
ok: true,
response: response.result.docs
})
})
app.get('/api/users/bytag', async (req, res) => {
console.log('GET /api/users/bytag')
// get all users by tag in reverse chrono order
const tag = req.query.tag
const response = await client.postFind({
db: USERDB,
selector: {tag:tag},
sort: [{
dateCreated: 'desc'
}],
limit: 50
})
res.send({
ok: true,
response: response.result.docs
})
})
// DELETE /users endpoint
app.delete('/api/users', async (req, res) => {
console.log('DELETE /users')
const todo = req.body
await client.deleteDocument({
db: USERDB,
docId: todo._id,
rev: todo._rev
})
res.send({ ok: true })
})
// Just for debugging !!
const populateUsers = async function () {
// find out if the db exists and if not create it
try {
await client.getDatabaseInformation({db:USERDB})
//if you get here the db exists so do nothing
console.log("Database exists")
return
} catch (error) {
//if you end up here you need to create the db
console.log("Database does not exist. Creating...")
}
try {
await client.putDatabase({db:USERDB})
//now create the indexes
await client.postIndex({
db: USERDB,
ddoc: 'bydate-index',
name: 'getUsersByAge',
index: {fields:["dateCreated"]},
type: 'json'
})
await client.postIndex({
db: USERDB,
ddoc: 'bytag-index',
name: 'getUsersByTag',
index: {fields:["tag", "dateCreated"]},
type: 'json'
})
//now add some sample data
await client.postDocument({
db:USERDB,
document: {
username: "zazapachulia",
dateCreated: new Date().toISOString(),
tag: "verified",
contributions: []
}
})
await client.postDocument({
db:USERDB,
document: {
username: "LaVar James",
dateCreated: new Date().toISOString(),
tag: "unverified",
contributions: []
}
})
} catch (error) {
console.log("Failed to create database or indexes: ", error)
return
}
}
const createStoryboards = async function() {
try {
await client.getDatabaseInformation({db: STORYDB})
console.log("Storyboard DB exists");
return
}
catch(error){
console.log("Database DNE, creating storyboard database...");
}
try {
await client.putDatabase({db: STORYDB})
} catch (error) {
console.log("Error creating database lol haha get rekt git pwnde");
}
}
const main = async function () {
await populateUsers();
await createStoryboards();
// start the webserver
app.listen(PORT, HOST)
console.log(`Running on http://${HOST}:${PORT}`)
}
main()