index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. function Caseless (dict) {
  2. this.dict = dict
  3. }
  4. Caseless.prototype.set = function (name, value, clobber) {
  5. if (typeof name === 'object') {
  6. for (var i in name) {
  7. this.set(i, name[i], value)
  8. }
  9. } else {
  10. if (typeof clobber === 'undefined') clobber = true
  11. var has = this.has(name)
  12. if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
  13. else this.dict[has || name] = value
  14. return has
  15. }
  16. }
  17. Caseless.prototype.has = function (name) {
  18. var keys = Object.keys(this.dict)
  19. , name = name.toLowerCase()
  20. ;
  21. for (var i=0;i<keys.length;i++) {
  22. if (keys[i].toLowerCase() === name) return keys[i]
  23. }
  24. return false
  25. }
  26. Caseless.prototype.get = function (name) {
  27. name = name.toLowerCase()
  28. var result, _key
  29. var headers = this.dict
  30. Object.keys(headers).forEach(function (key) {
  31. _key = key.toLowerCase()
  32. if (name === _key) result = headers[key]
  33. })
  34. return result
  35. }
  36. Caseless.prototype.swap = function (name) {
  37. var has = this.has(name)
  38. if (!has) throw new Error('There is no header than matches "'+name+'"')
  39. this.dict[name] = this.dict[has]
  40. delete this.dict[has]
  41. }
  42. Caseless.prototype.del = function (name) {
  43. var has = this.has(name)
  44. return delete this.dict[has || name]
  45. }
  46. module.exports = function (dict) {return new Caseless(dict)}
  47. module.exports.httpify = function (resp, headers) {
  48. var c = new Caseless(headers)
  49. resp.setHeader = function (key, value, clobber) {
  50. return c.set(key, value, clobber)
  51. }
  52. resp.hasHeader = function (key) {
  53. return c.has(key)
  54. }
  55. resp.getHeader = function (key) {
  56. return c.get(key)
  57. }
  58. resp.removeHeader = function (key) {
  59. return c.del(key)
  60. }
  61. resp.headers = c.dict
  62. return c
  63. }