forked from elgris/microservice-app-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodoController.js
96 lines (80 loc) · 2.54 KB
/
todoController.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
'use strict';
const cache = require('memory-cache');
const {Annotation,
jsonEncoder: {JSON_V2}} = require('zipkin');
const OPERATION_CREATE = 'CREATE',
OPERATION_DELETE = 'DELETE';
class TodoController {
constructor({tracer, redisClient, logChannel}) {
this._tracer = tracer;
this._redisClient = redisClient;
this._logChannel = logChannel;
}
// TODO: these methods are not concurrent-safe
list (req, res) {
const data = this._getTodoData(req.user.username)
res.json(data.items)
}
create (req, res) {
// TODO: must be transactional and protected for concurrent access, but
// the purpose of the whole example app it's enough
const data = this._getTodoData(req.user.username)
const todo = {
content: req.body.content,
id: data.lastInsertedID
}
data.items[data.lastInsertedID] = todo
data.lastInsertedID++
this._setTodoData(req.user.username, data)
this._logOperation(OPERATION_CREATE, req.user.username, todo.id)
res.json(todo)
}
delete (req, res) {
const data = this._getTodoData(req.user.username)
const id = req.params.taskId
delete data.items[id]
this._setTodoData(req.user.username, data)
this._logOperation(OPERATION_DELETE, req.user.username, id)
res.status(204)
res.send()
}
_logOperation (opName, username, todoId) {
this._tracer.scoped(() => {
const traceId = this._tracer.id;
this._redisClient.publish(this._logChannel, JSON.stringify({
zipkinSpan: traceId,
opName: opName,
username: username,
todoId: todoId,
}))
})
}
_getTodoData (userID) {
var data = cache.get(userID)
if (data == null) {
data = {
items: {
'1': {
id: 1,
content: "Create new todo",
},
'2': {
id: 2,
content: "Update me",
},
'3': {
id: 3,
content: "Delete example ones",
}
},
lastInsertedID: 3
}
this._setTodoData(userID, data)
}
return data
}
_setTodoData (userID, data) {
cache.put(userID, data)
}
}
module.exports = TodoController