« index

Coverage for /Users/yunong/workspace/node-restify/lib/plugins/accept.js : 97%

48 lines | 47 run | 1 missing | 0 partial | 7 blocks | 6 blocks run | 1 blocks missing

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

  // Copyright 2012 Mark Cavage, Inc.  All rights reserved.
  
  var assert = require('assert-plus');
  var mime = require('mime');
  
  var NotAcceptableError = require('../errors').NotAcceptableError;
  
  
  /**
   * Returns a plugin that will check the client's Accept header can be handled
   * by this server.
   *
   * Note you can get the set of types allowed from a restify server by doing
   * `server.acceptable`.
   *
   * @param {String} array of accept types.
   * @return {Function} restify handler.
   * @throws {TypeError} on bad input
   */
  function acceptParser(acceptable) {
      if (!Array.isArray(acceptable))
          acceptable = [acceptable];
      assert.arrayOfString(acceptable, 'acceptable');
  
      acceptable = acceptable.filter(function (a) {
          return (a);
      }).map(function (a) {
              return ((a.indexOf('/') === -1) ? mime.lookup(a) : a);
          }).filter(function (a) {
              return (a);
          });
  
      var e = new NotAcceptableError('Server accepts: ' + acceptable.join());
  
      function parseAccept(req, res, next) {
          if (req.accepts(acceptable)) {
              next();
              return;
          }
  
          res.json(e);
          next(false);
      }
  
      return (parseAccept);
  }
  
  module.exports = acceptParser;
« index | cover.io