webservice.js
4.7 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//
// (C) 2011, Nodejitsu Inc.
// MIT License
//
// A simple web service for storing JSON data via REST
//
// GET - View Object
// POST - Create Object
// PUT - Update Object
// DELETE - Delete Object
//
var revalidator = require('../'),
http = require('http'),
//
// Keep our objects in a simple memory store
//
memoryStore = {},
//
// Set up our request schema
//
schema = {
properties: {
url: {
description: 'the url the object should be stored at',
type: 'string',
pattern: '^/[^#%&*{}\\:<>?\/+]+$',
required: true
},
challenge: {
description: 'a means of protecting data (insufficient for production, used as example)',
type: 'string',
minLength: 5
},
body: {
description: 'what to store at the url',
type: 'any',
default: null
}
}
}
var server = http.createServer(function validateRestRequest (req, res) {
req.method = req.method.toUpperCase();
//
// Log the requests
//
console.log(req.method, req.url);
//
// Buffer the request so it can be parsed as JSON
//
var requestBody = [];
req.on('data', function addDataToBody (data) {
requestBody.push(data);
});
//
// Once the request has ended work with the body
//
req.on('end', function dealWithRest () {
//
// Parse the JSON
//
requestBody = requestBody.join('');
if ({POST: 1, PUT: 1}[req.method]) {
try {
requestBody = JSON.parse(requestBody);
}
catch (e) {
res.writeHead(400);
res.end(e);
return;
}
}
else {
requestBody = {};
}
//
// If this was sent to a url but the body url was not declared
// Make sure the body get the requested url so that our schema
// validates before we work on it
//
if (!requestBody.url) {
requestBody.url = req.url;
}
//
// Don't let users override the main API endpoint
//
if (requestBody.url === '/') {
res.writeHead(400);
res.end('Cannot override the API endpoint "/"');
return;
}
//
// See if our request and target are out of sync
// This lets us double check the url we are about to take up
// if we choose to send the request to the url directly
//
if (req.url !== '/' && requestBody.url !== req.url) {
res.writeHead(400);
res.end('Requested url and actual url do not match');
return;
}
//
// Validate the schema
//
var validation = revalidator.validate(requestBody, schema);
if (!validation.valid) {
res.writeHead(400);
res.end(validation.errors.join('\n'));
return;
}
//
// Grab the current value from storage and
// check if it is a valid state for REST
//
var storedValue = memoryStore[requestBody.url];
if (req.method === 'POST') {
if (storedValue) {
res.writeHead(400);
res.end('ALREADY EXISTS');
return;
}
}
else if (!storedValue) {
res.writeHead(404);
res.end('DOES NOT EXIST');
return;
}
//
// Check our challenge
//
if (storedValue && requestBody.challenge != storedValue.challenge) {
res.writeHead(403);
res.end('NOT AUTHORIZED');
return;
}
//
// Since revalidator only checks and does not manipulate
// our object we need to set up the defaults our selves
// For an easier solution to this please look at Flatiron's
// `Resourceful` project
//
if (requestBody.body === undefined) {
requestBody.body = schema.properties.body.default;
}
//
// Use REST to determine how to manipulate the stored
// values
//
switch (req.method) {
case "GET":
res.writeHead(200);
var result = storedValue.body;
res.end(JSON.stringify(result));
return;
case "POST":
res.writeHead(201);
res.end();
memoryStore[requestBody.url] = requestBody;
return;
case "DELETE":
delete memoryStore[requestBody.url];
res.writeHead(200);
res.end();
return;
case "PUT":
memoryStore[requestBody.url] = requestBody;
res.writeHead(200);
res.end();
return;
default:
res.writeHead(400);
res.end('Invalid Http Verb');
return;
}
});
})
//
// Listen to various ports depending on environment we are being run on
//
server.listen(process.env.PORT || process.env.C9_PORT || 1337, function reportListening () {
console.log('JSON REST Service listening on port', this.address().port);
console.log('Requests can be sent via REST to "/" if they conform to the following schema:');
console.log(JSON.stringify(schema, null, ' '));
});