forked from cyclic-software/starter-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (63 loc) · 2.28 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
const express = require('express')
const app = express()
const db = require('@cyclic.sh/dynamodb')
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// #############################################################################
// This configures static hosting for files in /public that have the extensions
// listed in the array.
// var options = {
// dotfiles: 'ignore',
// etag: false,
// extensions: ['htm', 'html','css','js','ico','jpg','jpeg','png','svg'],
// index: ['index.html'],
// maxAge: '1m',
// redirect: false
// }
// app.use(express.static('public', options))
// #############################################################################
// Create or Update an item
app.post('/:col/:key', async (req, res) => {
console.log(req.body)
const col = req.params.col
const key = req.params.key
console.log(`from collection: ${col} delete key: ${key} with params ${JSON.stringify(req.params)}`)
const item = await db.collection(col).set(key, req.body)
console.log(JSON.stringify(item, null, 2))
res.json(item).end()
})
// Delete an item
app.delete('/:col/:key', async (req, res) => {
const col = req.params.col
const key = req.params.key
console.log(`from collection: ${col} delete key: ${key} with params ${JSON.stringify(req.params)}`)
const item = await db.collection(col).delete(key)
console.log(JSON.stringify(item, null, 2))
res.json(item).end()
})
// Get a single item
app.get('/:col/:key', async (req, res) => {
const col = req.params.col
const key = req.params.key
console.log(`from collection: ${col} get key: ${key} with params ${JSON.stringify(req.params)}`)
const item = await db.collection(col).get(key)
console.log(JSON.stringify(item, null, 2))
res.json(item).end()
})
// Get a full listing
app.get('/:col', async (req, res) => {
const col = req.params.col
console.log(`list collection: ${col} with params: ${JSON.stringify(req.params)}`)
const items = await db.collection(col).list()
console.log(JSON.stringify(items, null, 2))
res.json(items).end()
})
// Catch all handler for all other request.
app.use('*', (req, res) => {
res.json({ msg: 'no route handler found' }).end()
})
// Start the server
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`index.js listening on ${port}`)
})