-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
103 lines (100 loc) · 3.05 KB
/
app.js
File metadata and controls
103 lines (100 loc) · 3.05 KB
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')
const app = express();
app.use(express.static('public'))
//app.use(express.static(__dirname));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
const fs = require('fs')
const {promisify} = require('util');
const filePath = './public/data.json'
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
app.use(function (req, res, next) {
console.log('url:', req.url)
next()
})
app.get('/', function (req, res) {
(async () => {
let data = await readFile(filePath, 'utf8')
res.status(200).json(JSON.parse(data))
})()
})
app.get('/recipes/details/*', function (req, res) {
(async () => {
let content = await readFile(filePath, 'utf8')
let data = JSON.parse(content)
let recipeName = req.url.slice(17)
let retData = {}
for (let i in data.recipes) {
let item = data.recipes[i]
if (item.name === recipeName) {
retData = {
details:
{
"ingredients": [],
"numSteps": []
},
}
retData.details.ingredients = item.ingredients
retData.details.numSteps = item.instructions.length
}
}
res.status(200).json(retData)
})()
})
app.get('/recipes', function (req, res) {
(async () => {
let content = await readFile(filePath, 'utf8')
let data = JSON.parse(content)
let retData = {
recipeNames: []
}
for (let i in data.recipes) {
let item = data.recipes[i]
retData.recipeNames.push(item.name)
}
res.status(200).json(retData)
})()
})
app.post('/recipes', function(req,res) {
(async () => {
let content = await readFile(filePath, 'utf8')
let data = JSON.parse(content)
let inputName = req.body.name
for(let i in data.recipes) {
let item = data.recipes[i]
if(inputName === item.name) {
const errRet = {
error:"Recipe already exists"
}
res.status(400).json(errRet)
return
}
}
data.recipes.push(req.body)
await writeFile(filePath,JSON.stringify(data))
res.sendStatus(201)
})()
})
app.put('/recipes',function(req,res) {
(async () => {
let content = await readFile(filePath, 'utf8')
let data = JSON.parse(content)
let inputName = req.body.name
for(let i in data.recipes) {
let item = data.recipes[i]
if(inputName === item.name) {
//Update and return
data.recipes[i] = req.body
await writeFile(filePath,JSON.stringify(data))
res.sendStatus(204)
return
}
}
const errRet = {
error:"Recipe does not exist"
}
res.status(404).json(errRet)
})()
})
module.exports = app