-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddressBookServer.js
More file actions
678 lines (638 loc) · 21.9 KB
/
AddressBookServer.js
File metadata and controls
678 lines (638 loc) · 21.9 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
var http = require("http");
function parseJSONContent(req, res) {
var text = req.body;
try {
return JSON.parse(text);
} catch (err) {
console.log("Failed to parse content as JSON: " + text);
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Failed to parse content as JSON</body></html>");
return undefined;
}
}
var dispatcher = (function() {
var handlers = [];
function findHandler(url, method) {
method = method.toLowerCase();
var urlMatches = false;
var index = 0;
var handler = null;
for (index = 0; index < handlers.length; index++) {
handler = handlers[index];
if (handler.pattern instanceof RegExp && handler.pattern.test(url)) {
urlMatches = true;
if (handler.method === method) return handler;
} else if (handler.pattern === url) {
urlMatches = true;
if (handler.method === method) return handler;
}
}
if (urlMatches) return null;
return undefined;
}
function addHandler(method, urlPattern, callback, hasData) {
method = method.toLowerCase();
var handler = {
pattern: urlPattern,
callback: callback,
method: method,
hasData: hasData
};
handlers.push(handler);
}
function fetchStatic(req, res) {
var url = require("url").parse(req.url, true);
var path = require("path");
var pathName = (url.pathname === "/" ? "/index.html" : url.pathname);
var fileName = "." + path.sep + path.join("webroot", pathName);
var fs = require("fs");
var mime = require("mime");
var found = false;
if (req.method.toLowerCase() === "get") {
console.log("RETRIEVING: " + fileName);
fs.readFile(fileName, function(err, file) {
if (err) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Resource not found: " + req.url + "</body></html>");
return;
}
found = true;
res.writeHead(200, {"Content-Type": mime.lookup(fileName)});
res.write(file, "binary");
res.end();
});
} else {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Resource not found: " + req.url + "</body></html>");
}
}
return {
onGet: function(urlPattern, callback) {
addHandler("get", urlPattern, callback, false);
},
onPost: function(urlPattern, callback) {
addHandler("post", urlPattern, callback, true);
},
onPut: function(urlPattern, callback) {
addHandler("put", urlPattern, callback, true);
},
onDelete: function(urlPattern, callback) {
addHandler("delete", urlPattern, callback, false);
},
dispatch: function(req, res) {
var handler = findHandler(req.url, req.method);
if (handler === undefined) {
fetchStatic(req, res);
return;
}
if (handler === null) {
res.writeHead(405, {"Content-Type":"text/html"});
res.end("<html><body>Method " + req.method + " not allowed for "
+ req.url + "</body></html>");
return;
}
if (handler.hasData) {
req.on("data", function(data) {
if (!req.body) {
req.body = data;
} else {
req.body += data;
}
});
req.on("end", function() {
handler.callback(req, res);
});
} else {
handler.callback(req, res);
}
}
};
})();
var nextID = 1001;
var phoneTypes = [
"Home Phone",
"Mobile Phone",
"Work Phone",
"Main Phone",
"Other Phone"
];
var addressTypes = [
"Home Address",
"Mailing Address",
"Work Address",
"Other Address"
];
var data = [
{
"contactID": nextID++,
"givenName": "John",
"surname": "Doe",
"phoneNumbers": [
{
"phoneID": nextID++,
"phoneType": "Home Phone",
"phoneNumber": "415-555-1212"
},
{
"phoneID": nextID++,
"phoneType": "Mobile Phone",
"phoneNumber": "415-555-1313"
}
],
"addresses": [
{
"addressID": nextID++,
"addressType": "Home Address",
"street": "101 Main Street",
"city": "Somewhere",
"state": "CA",
"postalCode": "90001"
},
{
"addressID": nextID++,
"addressType": "Work Address",
"street": "101 First Street",
"city": "Somewhere",
"state": "CA",
"postalCode": "90002"
}
]
},
{
"contactID": nextID++,
"givenName": "Jane",
"surname": "Smith",
"phoneNumbers": [
{
"phoneID": nextID++,
"phoneType": "Home Phone",
"phoneNumber": "415-555-2222"
},
{
"phoneID": nextID++,
"phoneType": "Mobile Phone",
"phoneNumber": "415-555-3333"
}
],
"addresses": [
{
"addressID": nextID++,
"addressType": "Home Address",
"street": "200 Mayberry Street",
"city": "Nowhere",
"state": "CA",
"postalCode": "90003"
},
{
"addressID": nextID++,
"addressType": "Work Address",
"street": "300 Mulberry Street",
"city": "Nowhere",
"state": "CA",
"postalCode": "90004"
}
]
},
{
"contactID": nextID++,
"givenName": "Joe",
"surname": "Schmoe",
"phoneNumbers": [
{
"phoneID": nextID++,
"phoneType": "Mobile Phone",
"phoneNumber": "415-555-4444"
}
],
"addresses": [
{
"addressID": nextID++,
"addressType": "Home Address",
"street": "500 Fifth Ave",
"city": "Someplace",
"state": "CA",
"postalCode": "90005"
}
]
},
{
"contactID": nextID++,
"givenName": "Jill",
"surname": "Jones",
"phoneNumbers": [
{
"phoneID": nextID++,
"phoneType": "Mobile Phone",
"phoneNumber": "415-555-1717"
}
],
"addresses": [
{
"addressID": nextID++,
"addressType": "Home Address",
"street": "300 Village Ave",
"city": "Anywhere",
"state": "CA",
"postalCode": "90006"
}
]
},
{
"contactID": nextID++,
"givenName": "Bill",
"surname": "Rogers",
"phoneNumbers": [
{
"phoneID": nextID++,
"phoneType": "Mobile Phone",
"phoneNumber": "415-555-8888"
}
],
"addresses": [
{
"addressID": nextID++,
"addressType": "Home Address",
"street": "200 Second Street",
"city": "Anytown",
"state": "CA",
"postalCode": "90006"
}
]
}
];
const PORT = process.env.PORT || 3000;
//const PORT=18080;
function handleRequest(request, response) {
try {
console.log(request.url);
dispatcher.dispatch(request, response);
} catch(err) {
console.log("CAUGHT IT");
console.log(err);
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Server listening on http://localhost:" + PORT);
});
function createPhone(inbound) {
var newPhone = {};
newPhone.phoneType = inbound["phoneType"];
if (!newPhone.phoneType || phoneTypes.indexOf(newPhone.phoneType)<0) {
return null;
}
newPhone.phoneID = nextID++;
newPhone.phoneNumber = inbound["phoneNumber"];
return newPhone;
};
function updatePhone(existing, inbound) {
if ("phoneType" in inbound) {
if (!inbound.phoneType || phoneTypes.indexOf(inbound.phoneType)<0) {
return null;
}
existing.phoneType = inbound.phoneType;
}
if ("phoneNumber" in inbound) existing.phoneNumber = inbound.phoneNumber;
return existing;
};
function createAddress(inbound) {
var newAddr = {};
newAddr.addressType = inbound["addressType"];
if (!newAddr.addressType || addressTypes.indexOf(newAddr.addressType)<0) {
return null;
}
newAddr.addressID = nextID++;
newAddr.street = inbound["street"];
newAddr.city = inbound["city"];
newAddr.state = inbound["state"];
newAddr.postalCode = inbound["postalCode"];
return newAddr;
};
function updateAddress(existing, inbound) {
if ("addressType" in inbound) {
if (!inbound.addressType || addressTypes.indexOf(inbound.addressType)<0) {
return null;
}
existing.addressType = inbound.addressType;
}
if ("street" in inbound) existing.street = inbound.street;
if ("city" in inbound) existing.city = inbound.city;
if ("state" in inbound) existing.state = inbound.state;
if ("postalCode" in inbound) existing.postalCode = inbound.postalCode;
return existing;
};
function createContact(inbound) {
var newContact = {};
var error = false;
newContact.contactID = nextID++;
newContact.givenName = inbound.givenName;
newContact.surname = inbound.surname;
newContact.phoneNumbers = [];
newContact.addresses = [];
return newContact;
};
function findContact(contactID) {
var found = null;
data.forEach(function(contact) {
if (contact.contactID === contactID && found === null) {
found = contact;
}
});
return found;
}
function findPhone(phoneNumbers, phoneID) {
var index = 0;
for (index = 0; index < phoneNumbers.length; index++) {
if (phoneNumbers[index].phoneID === phoneID) {
return index;
}
}
return -1;
}
function findAddress(addresses, addressID) {
var index = 0;
for (index = 0; index < addresses.length; index++) {
if (addresses[index].addressID === addressID) {
return index;
}
}
return -1;
}
function truncateContact(contact) {
return {
contactID: contact.contactID,
givenName: contact.givenName,
surname: contact.surname
};
}
//dispatcher.setStatic("resources");
dispatcher.onGet("/contacts", function(req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
var result = [];
data.forEach(function(contact) {
result.push(truncateContact(contact));
});
res.end(JSON.stringify(result));
});
dispatcher.onPost("/contacts", function(req, res) {
var inbound = parseJSONContent(req, res);
if (inbound === undefined) return;
var newContact = createContact(inbound);
if (!newContact) {
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Bad Input</body></html>")
} else {
data.push(newContact);
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(truncateContact(newContact)));
}
});
const contactRegExp = /^\/contacts\/(\d+)$/;
dispatcher.onGet(contactRegExp, function(req, res) {
console.log("GOT HERE!!!!");
var contactID = parseInt(req.url.replace(contactRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
} else {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(truncateContact(found)));
}
});
dispatcher.onPut(contactRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(contactRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Contact " + contactID + "</body></html>");
return;
}
var inbound = parseJSONContent(req,res);
if (inbound === undefined) return;
if ("givenName" in inbound) found.givenName = inbound.givenName;
if ("surname" in inbound) found.surname = inbound.surname;
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(truncateContact(found)));
});
dispatcher.onDelete(contactRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(contactRegExp,"$1"));
var index = 0, found = false;
for (index = 0; index < data.length; index++) {
if (data[index].contactID === contactID) {
found = true;
break;
}
}
if (found) {
data.splice(index, 1);
}
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<html><body>Deleted Contact " + contactID + "</body></html>");
});
dispatcher.onGet("/phone-types", function(req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(phoneTypes));
});
const phonesRegExp = /^\/contacts\/(\d+)\/phones$/;
dispatcher.onGet(phonesRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(phonesRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(found.phoneNumbers ? found.phoneNumbers : []));
});
dispatcher.onPost(phonesRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(phonesRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
return;
}
var inbound = parseJSONContent(req, res);
if (inbound === undefined) return;
var newPhone = createPhone(inbound);
if (!newPhone) {
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Bad Input</body></html>");
return;
}
found.phoneNumbers.push(newPhone);
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(newPhone));
});
const phoneRegExp = /^\/contacts\/(\d+)\/phones\/(\d+)$/;
dispatcher.onGet(phoneRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(phoneRegExp,"$1"));
var phoneID = parseInt(req.url.replace(phoneRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
return;
}
var phoneIndex = findPhone(found.phoneNumbers, phoneID);
if (phoneIndex < 0) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find phone " + phoneID
+ " for contact " + contactID + "</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(found.phoneNumbers[phoneIndex]));
});
dispatcher.onPut(phoneRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(phoneRegExp,"$1"));
var phoneID = parseInt(req.url.replace(phoneRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Contact " + contactID + "</body></html>");
return;
}
var phoneIndex = findPhone(found.phoneNumbers, phoneID);
if (phoneIndex < 0) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Phone " + phoneID + " for Contact "
+ contactID + "</body></html>");
return;
}
var inbound = parseJSONContent(req, res);
if (inbound === undefined) return;
var foundPhone = updatePhone(found.phoneNumbers[phoneIndex], inbound);
if (!foundPhone) {
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Bad Input</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(foundPhone));
});
dispatcher.onDelete(phoneRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(phoneRegExp,"$1"));
var phoneID = parseInt(req.url.replace(phoneRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Contact " + contactID + "</body></html>");
return;
}
var phoneIndex = findPhone(found.phoneNumbers, phoneID);
if (phoneIndex >= 0) {
found.phoneNumbers.splice(phoneIndex, 1);
}
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<html><body>Deleted Phone " + phoneID + " from Contact " + contactID
+ "</body></html>");
});
dispatcher.onGet("/address-types", function(req, res) {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(addressTypes));
});
const addressesRegExp = /^\/contacts\/(\d+)\/addresses$/;
dispatcher.onGet(addressesRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(addressesRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(found.addresses ? found.addresses : []));
});
dispatcher.onPost(addressesRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(addressesRegExp,"$1"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find contact: " + contactID
+ "</body></html>");
return;
}
var inbound = parseJSONContent(req, res);
if (inbound === undefined) return;
var newAddress = createAddress(inbound);
if (!newAddress) {
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Bad Input</body></html>");
return;
}
found.addresses.push(newAddress);
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(newAddress));
});
const addressRegExp = /^\/contacts\/(\d+)\/addresses\/(\d+)$/;
dispatcher.onGet(addressRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(addressRegExp,"$1"));
var addressID = parseInt(req.url.replace(addressRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("Did not find contact: " + contactID);
return;
}
var addrIndex = findAddress(found.addresses, addressID);
if (addrIndex < 0) {
res.writeHead(404, {"Content-Type":"text/html"});
res.end("<html><body>Did not find address " + addressID
+ " for contact " + contactID + "</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(found.addresses[addrIndex]));
});
dispatcher.onPut(addressRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(addressRegExp,"$1"));
var addressID = parseInt(req.url.replace(addressRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Contact " + contactID + "</body></html>");
return;
}
var addrIndex = findAddress(found.addresses, addressID);
if (addrIndex < 0) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Address " + addressID + " for Contact "
+ contactID + "</body></html>");
return;
}
var inbound = parseJSONContent(req, res);
if (inbound === undefined) return;
var foundAddr = updateAddress(found.addresses[addrIndex], inbound);
if (!foundAddr) {
res.writeHead(400, {"Content-Type": "text/html"});
res.end("<html><body>Bad Input</body></html>");
return;
}
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(foundAddr));
});
dispatcher.onDelete(addressRegExp, function(req, res) {
var contactID = parseInt(req.url.replace(addressRegExp,"$1"));
var addressID = parseInt(req.url.replace(addressRegExp,"$2"));
var found = findContact(contactID);
if (!found) {
res.writeHead(404, {"Content-Type": "text/html"});
res.end("<html><body>Not Found: Contact " + contactID + "</body></html>");
return;
}
var addrIndex = findAddress(found.addresses, addressID);
if (addrIndex >= 0) {
found.addresses.splice(addrIndex, 1);
}
res.writeHead(200, {"Content-Type": "text/html"});
res.end("<html><body>Deleted Address " + addressID + " from Contact " + contactID
+ "</body></html>");
});