Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. 'use strict'
  2.  
  3. class Router {
  4. constructor() {
  5. this.stack = {
  6. GET: {},
  7. POST: {}
  8. }
  9. }
  10.  
  11. init(request, response) {
  12. let handler = this.stack[request.method][request.url]
  13.  
  14. if (typeof handler === 'function') {
  15. return handler.apply(this, [request, response])
  16. } else {
  17. response.writeHead(404, { 'Content-Type': 'text/plain' })
  18. response.write(`Cannot ${request.method} ${request.url}`)
  19. response.end()
  20. }
  21. }
  22.  
  23. get(...args) {
  24. if (args.length === 2) {
  25. let [path, handler] = args
  26.  
  27. if (typeof path !== 'string' || !path.startsWith('/')) {
  28. console.error(new TypeError('The path is not correct'))
  29. } else if (typeof handler !== 'function') {
  30. console.error(new TypeError('The handler is not a function'))
  31. } else {
  32. this.stack['GET'][path] = handler
  33. }
  34. } else {
  35. console.error(new TypeError('The parameters are not corrects'))
  36. }
  37. }
  38.  
  39. post(...args) {
  40. if (args.length === 2) {
  41. let [path, handler] = args
  42.  
  43. if (typeof path !== 'string' && !path.startsWith('/')) {
  44. console.error(new TypeError('The path is not correct'))
  45. } else if (typeof handler !== 'function') {
  46. console.error(new TypeError('The handler is not a function'))
  47. } else {
  48. this.stack['POST'][path] = handler
  49. }
  50. } else {
  51. console.error(new TypeError('The parameters are not corrects'))
  52. }
  53. }
  54. }
  55.  
  56. module.exports = Router
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement