-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExternalDB.js
executable file
·108 lines (88 loc) · 2.55 KB
/
ExternalDB.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
97
98
99
100
101
102
103
104
105
106
107
108
var http = require('http')
module.exports = {
/**
* Create HTTP Request containing a key value as its data to utilise a
* storage service.
* @pararms { STRING } k - key
* @params { FUNCTION } callback - function that takes status code and output of request.
*/
read: function ( k, callback ) {
var options = {
host: 'localhost',
port: 3000,
path: '/part1/' + k
}
var req = http.get(options, function(res) {
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
callback( res.statusCode, JSON.parse( body ) )
})
})
},
/**
* Creates HTTP Request containing a key value pair as its data. Pointing at
* storage service of part 1
* @params { JSON OBJECT } kv - A key and a value object.
* @params { FUNCTION } callback - function that takes status code and output of request.
*/
insert: function ( kv, callback ) {
var options = {
host: 'localhost',
port: 3000,
path: '/part1/',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength( JSON.stringify(kv) )
}
}
// Set up the request
var post_req = http.request( options, function(res) {
res.setEncoding('utf8');
res.on('data', function ( data ) {
callback( res.statusCode, JSON.parse( data ) )
});
});
// post the data
post_req.write( JSON.stringify(kv) )
post_req.end();
},
/**
* Creates HTTP Request containing a key value as its data. Pointing at
* storage service of part 1
* @pararms { STRING } k - key
* @params { FUNCTION } callback - function that takes status code and output of request.
*/
delete: function ( k, callback ) {
var payload = { key: k }
var options = {
host: 'localhost',
port: 3000,
path: '/part1/' + k,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength( JSON.stringify(payload) )
}
}
var post_req = http.request( options, function(res) {
res.setEncoding('utf8');
// Not expecting return data, boolean to ensure only one callback fires.
// data would be error info.
var submitted = false;
res.on('data', function ( data ) {
submitted = true
callback( res.statusCode, data )
}).on('end', function () {
if( !submitted ){
callback( res.statusCode, null )
}
})
})
post_req.write( JSON.stringify(payload) )
post_req.end();
}
}