Advertisement
Guest User

Untitled

a guest
Sep 25th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1.  
  2. var http = require('http'),
  3. fs = require('fs'),
  4. rl = require('readline'),
  5. mysql = require('mysql');
  6.  
  7. var connection = mysql.createConnection({
  8. host : 'localhost',
  9. user : 'root',
  10. password : 'admin123',
  11. database : 'employees'
  12. });
  13.  
  14. const PORT=8080;
  15.  
  16. var server = http.createServer(handleRequest);
  17.  
  18. var users = [];
  19. var tmpUser = {"first_name":"","last_name":"","email":"","country":"","ip_address":""};
  20.  
  21.  
  22. connection.connect();
  23.  
  24. function handleRequest(request, response){
  25. var splittedUrl = splitUrl(request.url);
  26. //askUser();
  27. switch(request.method){
  28. case "GET":
  29. if (splittedUrl.length == 2) {
  30. if (isCollectionUrl(splittedUrl)) {
  31. connection.query('SELECT * FROM "employees"', function(error,results,fields){
  32. response.end(write(JSON.stringify(results)));
  33. });
  34. }
  35. else if (isElementUrl(splittedUrl)) {
  36. response.end();
  37. }
  38. }
  39. break;
  40. case "POST":
  41. console.log("Request method is POST");
  42. break;
  43. }
  44. }
  45.  
  46. server.listen(PORT, function(){
  47. console.log("Server listening on: http://localhost:", PORT);
  48. });
  49.  
  50. function splitUrl(url) {
  51. var array = url.split("/");
  52. array.shift();
  53. return array;
  54. }
  55.  
  56. function isCollectionUrl(array){
  57. return (array[0] == "employees" && array[1] == "");
  58. }
  59. function isElementUrl(array) {
  60. return (array[0] == "employees" && array[1].match(/^\d+$/));
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement