/
index.js
65 lines (60 loc) · 1.9 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
const axios = require('axios')
const { appendFile } = require('fs').promises
const app = require('express')()
const bodyParser = require('body-parser')
const jsonRouter = require('../json-rpc')
function formatData(data, id = '') {
return `${id}: ${Date.now()} : ${JSON.stringify(data)}\n`
}
const controller = {
async getUser({ id }) {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`)
return response.data
},
async getPost({ id }) {
const response = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
return response.data
},
async getPhoto({ id }) {
const response = await axios.get(`https://jsonplaceholder.typicode.com/photos/${id}`)
return response.data
}
}
const beforeController = {
getUser({ id }) {
if (id <= 0 || id > 10) {
throw new Error('ERROR: getUser id should be between 1 and 10')
}
},
getPost({ id }) {
if (id <= 0 || id > 100) {
throw new Error('ERROR: getUserPosts id should be between 1 and 100')
}
},
getPhoto({ id }) {
if (id <= 0 || id > 5000) {
throw new Error('ERROR: getUserPhotos id should be between 1 and 5000')
}
}
}
const afterController = {
async getUser({ id }, execResult) {
await appendFile("users.log", formatData(execResult, id))
},
async getPost({ id }, execResult) {
await appendFile("posts.log", formatData(execResult, id))
},
async getPhoto({ id }, execResult) {
await appendFile("photos.log", formatData(execResult, id))
}
}
app.use(bodyParser.json())
app.use(jsonRouter({
methods: controller,
beforeMethods: beforeController,
afterMethods: afterController,
onError(e) {
console.log('Omg error occurred!', e)
}
}))
app.listen(3000, () => console.log('Example app listening on port 3000'))