Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. 'use strict'
  2.  
  3. var http = require('http')
  4. var url = require('url')
  5. var config = require('./config')
  6.  
  7. class TinyCacheServer {
  8. constructor(host, port){
  9. this.host = host
  10. this.port = port
  11.  
  12. this.projects = {}
  13.  
  14. this.server = http.createServer((req, res) => {
  15. this._handleRequest(req, res)
  16. })
  17. this.server.listen(this.port, this.host)
  18. }
  19. _handleRequest(req, res){
  20. var path = url.parse(req.url).path
  21.  
  22. var project = path.split('/')[1]
  23. var method = path.split('/')[2]
  24. var key = path.split('/')[3]
  25.  
  26. switch (method){
  27. case 'get':
  28. this._get(req, res, project, key)
  29. return
  30. case 'set':
  31. this._set(req, res, project, key)
  32. return
  33. case 'remove':
  34. this._remove(req, res, project, key)
  35. return
  36. default:
  37. res.end()
  38. }
  39. }
  40. _get(req, res, project, key){
  41. if(!project || !key || !this.projects[project] || !this.projects[project][key]) {
  42. res.end()
  43. return
  44. }
  45.  
  46. res.end(JSON.stringify(this.projects[project][key]))
  47. }
  48. _set(req, res, project, key){
  49. var chunks = []
  50.  
  51. req.on('data', (chunk) => {
  52. chunks.push(chunk)
  53. })
  54. .on('end', () => {
  55. var body = Buffer.concat(chunks).toString('utf-8').split('=')
  56.  
  57. if(body[0] !== 'value' || !key || !project){
  58. res.end()
  59. return
  60. }
  61. var data = JSON.parse(decodeURIComponent(body[1]))
  62.  
  63. if(!this.projects[project]){
  64. this.projects[project] = {}
  65. }
  66. this.projects[project][key] = data
  67.  
  68. res.end()
  69. })
  70. }
  71. _remove(req, res, project, key){
  72. res.end()
  73.  
  74. if(!project || !key || !this.data[key]) {
  75. return
  76. }
  77.  
  78. if(this.projects[project]){
  79. delete this.projects[project][key]
  80. }
  81. }
  82. }
  83.  
  84. new TinyCacheServer(config.host, config.port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement