-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
83 lines (74 loc) · 2.63 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
const express = require('express')
const app = express()
const cors = require('cors')
const knex = require('./knex')
const bodyParser = require('body-parser');
const { DatabaseError } = require('pg')
const PORT = process.env.PORT || 8080
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
app.set('port', PORT)
//TEST
app.get('/', (request, response) => {
response.status(200).json({
smoke: "test"
})
})
//Get all comics in collection
app.get('/api/v1/comicData', async (request, response) => {
const comicData = await knex.select().from('comicData')
response.status(200).json(comicData)
})
//Get single comic in collection
app.get('/api/v1/comicData/:id', async (request, response) => {
try {
const { id } = request.params
const comic = await knex.where('id', id).select().from('comicData')
if (comic.length) {
response.status(200).json(comic)
} else {
response.status(404).send(`Comic not found matching the id ${id}`)
}
} catch (err) {
response.status(500).send(err.message)
}
})
//Add new comic to collection
app.post('/api/v1/comicData', async (request, response) => {
for (let requiredParameter of ['title', 'year', 'issue', 'grade', 'image_path', 'verified', 'note']) {
if (!request.body[requiredParameter]) {
return response
.status(422)
.send({ error: `Expected format: {title: <String>, year: <String>, issue: <String>, grade: <String>, image_path: <String>, verified: <String>, note: <String>}. You're missing a "${requiredParameter}" property.` });
}
}
try {
const comic = await knex('comicData').insert(request.body, ['id', 'title', 'year', 'issue', 'grade', 'image_path', 'verified', 'note'])
response.status(201).json(comic[0])
} catch (error) {
console.error(error)
response.status(500).json(error)
}
})
//Update single comic in collection
app.put('/api/v1/comicData/:id', async (request, response) => {
try {
const comic = await knex('comicData').where('id', Number(request.params.id)).update(request.body, ['id', 'title', 'year', 'issue', 'grade', 'image_path', 'verified', 'note'])
response.status(200).json(comic[0])
} catch (error) {
response.status(500).json(error)
}
})
//Delete single comic from collection
app.delete('/api/v1/comicData/:id', async (request, response) => {
try {
await knex('comicData').where('id', Number(request.params.id)).del()
response.status(200).json({ response: `Comic with id:${request.params.id} was deleted` })
} catch (error) {
response.status(500).json(error)
}
})
app.listen(PORT, () => {
console.log(`Server has started on port ${PORT}`)
})