« index

Coverage for /Users/yunong/workspace/node-restify/lib/formatters/jsonp.js : 81%

38 lines | 31 run | 7 missing | 0 partial | 8 blocks | 2 blocks run | 6 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

  // Copyright 2012 Mark Cavage, Inc.  All rights reserved.
  
  
  ///--- Exports
  
  function formatJSONP(req, res, body) {
      if (!body) {
          res.setHeader('Content-Length', 0);
          return (null);
      }
  
      if (body instanceof Error) {
          if ((body.restCode || body.httpCode) && body.body) {
              body = body.body;
          } else {
              body = {
                  message: body.message
              };
          }
      }
  
      if (Buffer.isBuffer(body))
          body = body.toString('base64');
  
      var cb = req.query.callback || req.query.jsonp;
      var data;
      if (cb) {
          data = 'typeof ' + cb + ' === \'function\' && ' +
                  cb + '(' + JSON.stringify(body) + ');';
      } else {
          data = JSON.stringify(body);
      }
  
      res.setHeader('Content-Length', Buffer.byteLength(data));
      return (data);
  }
  
  module.exports = formatJSONP;
« index | cover.io