Skip to content
Browse files

add media matching function

  • Loading branch information...
1 parent d850745 commit 00d04788c401c25231ea2b3229239294a2ed4e9a @benblank benblank committed May 10, 2012
Showing with 45 additions and 1 deletion.
  1. +45 −1 src/Accept.coffee
View
46 src/Accept.coffee
@@ -168,7 +168,51 @@ getBestLanguageMatch = (candidates) ->
# Get the best media-type match, as per RFC 2616 section 14.1.
getBestMediaMatch = (candidates) ->
- null
+ acceptable = (parseMediaType parseParams candidate for candidate in candidates)
+
+ for candidate, i in acceptable
+ candidate.index = i
+ candidate.quality = 0
+ candidate.prec = -1
+
+ for accepted in this
+ prec = -1
+
+ if accepted.type is candidate.type
+ if accepted.subtype is candidate.subtype
+ prec = 2
+
+ for param, value of accepted.params when param isnt "q"
+ if candidate.params[param] is value
+ prec++
+ else if accepted.subtype is "*"
+ prec = 1
+ # If type matches, but subtype does not and isn't a wildcard, leave the precedence at -1.
+ else if accepted.type is "*" and accepted.subtype is "*"
+ # Lower than the precedence of any non-wildcard match, but higher than that of a non-match.
+ prec = 0
+
+ if prec > candidate.prec
+ candidate.prec = prec
+ candidate.quality = accepted.quality
+
+ acceptable.sort (a, b) ->
+ if a.quality < b.quality
+ return 1
+ if a.quality > b.quality
+ return -1
+ if a.prec < b.prec
+ return 1
+ if a.prec > b.prec
+ return 1
+
+ # If all else is equal, prefer earlier candidates.
+ if a.index > b.index
+ return -1
+ if a.index < b.index
+ return 1
+
+ candidates[acceptable[0].index] if acceptable[0].quality
# Build middleware with parsers for several accept header fields.
middleware = (req, res, next) ->

0 comments on commit 00d0478

Please sign in to comment.
Something went wrong with that request. Please try again.