« index

Coverage for /Users/yunong/workspace/node-restify/lib/response.js : 90%

299 lines | 272 run | 27 missing | 0 partial | 54 blocks | 39 blocks run | 15 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

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

  // Copyright 2012 Mark Cavage, Inc.  All rights reserved.
  
  var crypto = require('crypto');
  var http = require('http');
  var sprintf = require('util').format;
  
  var assert = require('assert-plus');
  var mime = require('mime');
  var once = require('once');
  
  var errors = require('./errors');
  var httpDate = require('./http_date');
  
  
  ///--- Globals
  
  var HttpError = errors.HttpError;
  var RestError = errors.RestError;
  
  var Response = http.ServerResponse;
  
  
  ///--- API
  
  Response.prototype.cache = function cache(type, options) {
      if (typeof (type) !== 'string') {
          options = type;
          type = 'public';
      }
  
      if (options && options.maxAge !== undefined) {
          assert.number(options.maxAge, 'options.maxAge');
          type += ', max-age=' + options.maxAge;
      }
  
      return (this.header('Cache-Control', type));
  };
  
  
  Response.prototype.noCache = function noCache() {
      // HTTP 1.1
      this.header('Cache-Control', 'no-cache, no-store, must-revalidate');
  
      // HTTP 1.0
      this.header('Pragma', 'no-cache');
  
      // Proxies
      this.header('Expires', '0');
  
      return (this);
  };
  
  
  Response.prototype.charSet = function charSet(type) {
      assert.string(type, 'charset');
  
      this._charSet = type;
  
      return (this);
  };
  
  
  Response.prototype.format = function format(body, cb) {
      var log = this.log;
      var formatter;
      var type = this.contentType || this.getHeader('Content-Type');
      var self = this;
  
      if (!type) {
          if (this.req.accepts(this.acceptable)) {
              type = this.req.accepts(this.acceptable);
          }
  
          if (!type) {
              // The importance of a status code outside of the
              // 2xx range probably outweighs that of unable being to
              // format the response body
              if (this.statusCode >= 200 && this.statusCode < 300)
                  this.statusCode = 406;
  
              return (null);
          }
      } else if (type.indexOf(';') !== '-1') {
          type = type.split(';')[0];
      }
  
      if (!(formatter = this.formatters[type])) {
          if (type.indexOf('/') === -1)
              type = mime.lookup(type);
  
          if (this.acceptable.indexOf(type) === -1)
              type = 'application/octet-stream';
  
          formatter = this.formatters[type] || this.formatters['*/*'];
  
          if (!formatter) {
              log.warn({
                  req: self.req
              }, 'no formatter found. Returning 500.');
              this.statusCode = 500;
              return (null);
          }
      }
  
      if (this._charSet) {
          type = type + '; charset=' + this._charSet;
      }
  
      this.setHeader('Content-Type', type);
  
      if (body instanceof Error && body.statusCode !== undefined)
          this.statusCode = body.statusCode;
      return (formatter.call(this, this.req, this, body, cb));
  };
  
  
  Response.prototype.get = function get(name) {
      assert.string(name, 'name');
  
      return (this.getHeader(name));
  };
  
  
  Response.prototype.getHeaders = function getHeaders() {
      return (this._headers || {});
  };
  Response.prototype.headers = Response.prototype.getHeaders;
  
  
  Response.prototype.header = function header(name, value) {
      assert.string(name, 'name');
  
      if (value === undefined)
          return (this.getHeader(name));
  
      if (value instanceof Date) {
          value = httpDate(value);
      } else if (arguments.length > 2) {
          // Support res.header('foo', 'bar %s', 'baz');
          var arg = Array.prototype.slice.call(arguments).slice(2);
          value = sprintf(value, arg);
      }
  
      var current = this.getHeader(name);
      // #779, don't use comma separated values for set-cookie, see
      // http://tools.ietf.org/html/rfc6265#section-3
      if (current && name.toLowerCase() !== 'set-cookie') {
          if (Array.isArray(current)) {
              current.push(value);
              value = current;
          } else {
              value = [current, value];
          }
      }
  
      this.setHeader(name, value);
      return (value);
  };
  
  
  Response.prototype.json = function json(code, object, headers) {
      if (!/application\/json/.test(this.header('content-type')))
          this.header('Content-Type', 'application/json');
  
      return (this.send(code, object, headers));
  };
  
  
  Response.prototype.link = function link(l, rel) {
      assert.string(l, 'link');
      assert.string(rel, 'rel');
  
      var _link = sprintf('<%s>; rel="%s"', l, rel);
      return (this.header('Link', _link));
  };
  
  
  Response.prototype.send = function send(code, body, headers) {
      var isHead = (this.req.method === 'HEAD');
      var log = this.log;
      var self = this;
  
      if (code === undefined) {
          this.statusCode = 200;
      } else if (code.constructor.name === 'Number') {
          this.statusCode = code;
          if (body instanceof Error) {
              body.statusCode = this.statusCode;
          }
      } else {
          headers = body;
          body = code;
          code = null;
      }
  
      headers = headers || {};
  
      if (log.trace()) {
          var _props = {
              code: self.statusCode,
              headers: headers
          };
          if (body instanceof Error) {
              _props.err = body;
          } else {
              _props.body = body;
          }
          log.trace(_props, 'response::send entered');
      }
  
      this._body = body;
  
      function _cb(err, _body) {
          self._data = _body;
          Object.keys(headers).forEach(function (k) {
              self.setHeader(k, headers[k]);
          });
  
          self.writeHead(self.statusCode);
  
          if (self._data && !(isHead || code === 204 || code === 304))
              self.write(self._data);
  
          self.end();
  
          if (log.trace())
              log.trace({res: self}, 'response sent');
      }
  
      if (body) {
          var ret = this.format(body, _cb);
          if (!(ret instanceof Response)) {
              _cb(null, ret);
          }
      } else {
          _cb(null, null);
      }
  
      return (this);
  };
  
  
  Response.prototype.set = function set(name, val) {
      var self = this;
  
      if (arguments.length === 2) {
          assert.string(name, 'name');
          this.header(name, val);
      } else {
          assert.object(name, 'object');
          Object.keys(name).forEach(function (k) {
              self.header(k, name[k]);
          });
      }
  
      return (this);
  };
  
  
  Response.prototype.status = function status(code) {
      assert.number(code, 'code');
  
      this.statusCode = code;
      return (code);
  };
  
  
  Response.prototype.toString = function toString() {
      var headers = this.getHeaders();
      var headerString = '';
      var str;
  
      Object.keys(headers).forEach(function (k) {
          headerString += k + ': ' + headers[k] + '\n';
      });
      str = sprintf('HTTP/1.1 %s %s\n%s',
          this.statusCode,
          http.STATUS_CODES[this.statusCode],
          headerString);
  
      return (str);
  };
  
  if (!Response.prototype.hasOwnProperty('_writeHead'))
      Response.prototype._writeHead = Response.prototype.writeHead;
  
  
  Response.prototype.writeHead = function restifyWriteHead() {
      this.emit('header');
  
      if (this.statusCode === 204 || this.statusCode === 304) {
          this.removeHeader('Content-Length');
          this.removeHeader('Content-MD5');
          this.removeHeader('Content-Type');
          this.removeHeader('Content-Encoding');
      }
  
      this._writeHead.apply(this, arguments);
  };
« index | cover.io