1 |
|
2 | var statusCodes = require("http").STATUS_CODES
|
3 | , fs = require("fs")
|
4 | , zlib = require("zlib")
|
5 | , accept = require("./accept.js").accept
|
6 | , cookie = require("./cookie.js")
|
7 | , getContent = require("./content.js")
|
8 | , mime = require("./mime.js")
|
9 | , util = require("../lib/util.js")
|
10 | , events = require("../lib/events")
|
11 | , empty = {}
|
12 | , defaultOptions = {
|
13 | maxURILength: 2000,
|
14 | maxBodySize: 1e6,
|
15 | memBodySize: 1e6,
|
16 | maxFields: 1000,
|
17 | maxFiles: 1000,
|
18 | maxFieldSize: 1000,
|
19 | maxFileSize: Infinity,
|
20 | negotiateAccept: accept([
|
21 | 'application/json;space=',
|
22 | 'text/csv;headers=no;delimiter=",";NULL=;br="\r\n"',
|
23 | 'application/sql;NULL=NULL;table=table;fields='
|
24 | ]),
|
25 | errors: {
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | "URIError": { code: 400 }
|
36 | }
|
37 | }
|
38 |
|
39 | require("../lib/fn")
|
40 | require("../lib/timing")
|
41 |
|
42 | Object.keys(statusCodes).forEach(function(code) {
|
43 | if (code >= 400) {
|
44 | this[statusCodes[code]] = { code: +code }
|
45 | }
|
46 | }, defaultOptions.errors)
|
47 |
|
48 | module.exports = function createApp(_options) {
|
49 | var uses = []
|
50 | , options = app.options = {}
|
51 |
|
52 | util.deepAssign(options, defaultOptions, _options)
|
53 | events.asEmitter(app)
|
54 |
|
55 | app.use = function appUse(method, path) {
|
56 | var fn
|
57 | , arr = Array.from(arguments)
|
58 | , len = arr.length
|
59 | , i = 2
|
60 | if (typeof method === "function") {
|
61 | method = path = null
|
62 | i = 0
|
63 | } else if (typeof path === "function") {
|
64 | path = method
|
65 | method = null
|
66 | i = 1
|
67 | }
|
68 | for (; i < len; ) {
|
69 | if (typeof arr[i] !== "function") throw Error("Not a function")
|
70 | uses.push(method, path, arr[i++])
|
71 | }
|
72 | return app
|
73 | }
|
74 |
|
75 | app.addMethod = addMethod
|
76 | app.initRequest = initRequest
|
77 | app.readBody = readBody
|
78 | app.static = require("./static.js")
|
79 | app.listen = require("./listen.js")
|
80 |
|
81 | addMethod("del", "DELETE")
|
82 | addMethod("get", "GET")
|
83 | addMethod("patch", "PATCH")
|
84 | addMethod("post", "POST")
|
85 | addMethod("put", "PUT")
|
86 |
|
87 | return app
|
88 |
|
89 | function app(req, res, _next) {
|
90 | var oldPath, oldUrl
|
91 | , tryCatch = true
|
92 | , usePos = 0
|
93 |
|
94 | next()
|
95 |
|
96 | function next(err) {
|
97 | if (err) {
|
98 | return sendError(res, options, err)
|
99 | }
|
100 | var method = uses[usePos]
|
101 | , path = uses[usePos + 1]
|
102 | , pos = usePos += 3
|
103 |
|
104 | if (
|
105 | method && method !== req.method ||
|
106 | path && path !== req.url.slice(0, path.length)
|
107 | ) {
|
108 | next()
|
109 | } else if (uses[pos - 1] === void 0) {
|
110 | if (typeof _next === "function") {
|
111 | _next()
|
112 | } else {
|
113 | res.sendStatus(404)
|
114 | }
|
115 | } else {
|
116 | method = uses[pos - 1]
|
117 | if (path) {
|
118 | oldPath = req.baseUrl
|
119 | oldUrl = req.url
|
120 | req.baseUrl = path
|
121 | req.url = req.url.slice(path.length) || "/"
|
122 | }
|
123 | if (tryCatch === true) {
|
124 | tryCatch = false
|
125 | try {
|
126 | method.call(app, req, res, path ? nextPath : next, options)
|
127 | } catch(e) {
|
128 | return sendError(res, options, e)
|
129 | }
|
130 | } else {
|
131 | method.call(app, req, res, path ? nextPath : next, options)
|
132 | }
|
133 | if (pos === usePos) {
|
134 | tryCatch = true
|
135 | }
|
136 | }
|
137 | }
|
138 | function nextPath(e) {
|
139 | req.baseUrl = oldPath
|
140 | req.url = oldUrl
|
141 | next(e)
|
142 | }
|
143 | }
|
144 |
|
145 | function addMethod(method, methodString) {
|
146 | app[method] = function() {
|
147 | var arr = uses.slice.call(arguments)
|
148 | if (typeof arr[0] === "function") {
|
149 | arr.unshift(null)
|
150 | }
|
151 | arr.unshift(methodString)
|
152 | return app.use.apply(app, arr)
|
153 | }
|
154 | }
|
155 | }
|
156 |
|
157 |
|
158 |
|
159 | function initRequest(req, res, next, opts) {
|
160 | var forwarded = req.headers[opts.ipHeader || "x-forwarded-for"]
|
161 | req.ip = forwarded ? forwarded.split(/[\s,]+/)[0] : req.connection.remoteAddress
|
162 | req.res = res
|
163 | res.req = req
|
164 | req.date = new Date()
|
165 | res.send = send
|
166 | res.sendStatus = sendStatus
|
167 | res.opts = req.opts = opts
|
168 |
|
169 |
|
170 |
|
171 |
|
172 | if (req.url.length > opts.maxURILength) {
|
173 | return sendError(res, opts, "URI Too Long")
|
174 |
|
175 | }
|
176 |
|
177 | req.originalUrl = req.url
|
178 | req.cookie = cookie.get
|
179 | req.content = getContent
|
180 |
|
181 | res.cookie = cookie.set
|
182 | res.link = setLink
|
183 | res.sendFile = sendFile
|
184 |
|
185 | next()
|
186 | }
|
187 |
|
188 |
|
189 | function send(body, _opts) {
|
190 | var res = this
|
191 | , head = res.req.headers
|
192 | , negod = res.opts.negotiateAccept(head.accept || head["content-type"] || "*")
|
193 | , format = negod.subtype || "json"
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 | if (!format) {
|
200 | return res.sendStatus(406)
|
201 | }
|
202 |
|
203 | if (typeof body !== "string") {
|
204 | negod.select = _opts && _opts.select || res.req.url.split("$select")[1] || ""
|
205 | if (format == "csv") {
|
206 | body = require("../lib/csv.js").encode(body, negod)
|
207 | } else if (format == "sql") {
|
208 | negod.re = /\D/
|
209 | negod.br = "),\n("
|
210 | negod.prefix = "INSERT INTO " +
|
211 | negod.table + (negod.fields ? " (" + negod.fields + ")" : "") + " VALUES ("
|
212 | negod.postfix = ");"
|
213 | body = require("../lib/csv.js").encode(body, negod)
|
214 | } else {
|
215 | body = JSON.stringify(body, null, +negod.space || negod.space)
|
216 | }
|
217 | }
|
218 |
|
219 | res.setHeader("Content-Type", mime[format])
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 | res.end(
|
226 | format === "json" ? body.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029") :
|
227 | body
|
228 | )
|
229 | }
|
230 |
|
231 | var errIsDir = {
|
232 | name: "EISDIR",
|
233 | code: 403,
|
234 | message: "Is Directory"
|
235 | }
|
236 | , errBadRange = {
|
237 | name: "ERANGE",
|
238 | code: 416,
|
239 | message: "Range Not Satisfiable"
|
240 | }
|
241 | , flvMagic = "FLV" + String.fromCharCode(1,5,0,0,0,9,0,0,0,9)
|
242 | , ieRe = /\bMSIE (\d+)/
|
243 |
|
244 | function sendFile(file, _opts, next) {
|
245 | var res = this
|
246 | , opts = _opts || {}
|
247 |
|
248 | if (typeof opts === "function") {
|
249 | next = opts
|
250 | opts = {}
|
251 | }
|
252 |
|
253 | fs.stat(file, sendFile)
|
254 |
|
255 | function sendFile(err, stat) {
|
256 | if (err) {
|
257 | return next && next(err)
|
258 | }
|
259 |
|
260 | if (stat.isDirectory()) {
|
261 | return next && next(errIsDir)
|
262 | }
|
263 |
|
264 | var tmp
|
265 | , headers = {}
|
266 | , reqMtime = Date.parse(res.req.headers["if-modified-since"])
|
267 |
|
268 | if (reqMtime && reqMtime >= stat.mtime) {
|
269 | return res.sendStatus(304)
|
270 | }
|
271 |
|
272 | |
273 |
|
274 |
|
275 |
|
276 |
|
277 |
|
278 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 |
|
285 |
|
286 |
|
287 | if (typeof opts.maxAge === "number") {
|
288 | tmp = opts.cacheControl && opts.cacheControl[file]
|
289 | if (typeof tmp !== "number") tmp = opts.maxAge
|
290 |
|
291 |
|
292 | headers["Cache-Control"] = tmp > 0 ? "public, max-age=" + tmp : "no-cache"
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 | }
|
299 |
|
300 | if (opts.download) {
|
301 | headers["Content-Disposition"] = "attachment; filename=" + (
|
302 | opts.download === true ?
|
303 | file.split("/").pop() :
|
304 | opts.download
|
305 | )
|
306 | }
|
307 |
|
308 | |
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 |
|
315 |
|
316 |
|
317 | if (stat.size > opts.rangeSize) {
|
318 | headers["Accept-Ranges"] = "bytes"
|
319 | }
|
320 |
|
321 | var info = {
|
322 | code: 200,
|
323 | start: 0,
|
324 | end: stat.size,
|
325 | size: stat.size
|
326 | }
|
327 | , range = res.req.headers.range
|
328 |
|
329 | if (range = range && range.match(/bytes=(\d+)-(\d*)/)) {
|
330 |
|
331 |
|
332 |
|
333 | info.start = +range[1]
|
334 | info.end = +range[2]
|
335 |
|
336 | if (info.start > info.end || info.end > info.size) {
|
337 | res.setHeader("Content-Range", "bytes */" + info.size)
|
338 | return next && next(errBadRange)
|
339 | }
|
340 | info.code = 206
|
341 | info.size = info.end - info.start + 1
|
342 | headers["Content-Range"] = "bytes " + info.start + "-" + info.end + "/" + info.size
|
343 | }
|
344 |
|
345 | headers["Content-Type"] = mime[ file.split(".").pop() ] || mime["_default"]
|
346 | if (headers["Content-Type"].slice(0, 5) == "text/") {
|
347 | headers["Content-Type"] += "; charset=UTF-8"
|
348 | }
|
349 |
|
350 |
|
351 |
|
352 | headers["Content-Length"] = info.size
|
353 | res.writeHead(info.code, headers)
|
354 |
|
355 | if (res.req.method == "HEAD") {
|
356 | return res.end()
|
357 | }
|
358 |
|
359 | |
360 |
|
361 |
|
362 |
|
363 |
|
364 |
|
365 | if (info.start > 0 && info.mime === "video/x-flv") {
|
366 | res.write(flvMagic)
|
367 | }
|
368 |
|
369 | |
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 |
|
380 |
|
381 | if (headers["Content-Type"] == "text/html" && (tmp = ieRe.exec(req.headers["user-agent"]))) {
|
382 |
|
383 | res.setHeader("X-UA-Compatible", tmp[1] < 10 ? "IE=edge,chrome=1" : "IE=edge")
|
384 | }
|
385 |
|
386 | fs.createReadStream(file, {
|
387 | flags: "r",
|
388 | start: info.start,
|
389 | end: info.end
|
390 | }).pipe(res)
|
391 |
|
392 | |
393 |
|
394 |
|
395 |
|
396 |
|
397 |
|
398 |
|
399 |
|
400 |
|
401 |
|
402 | }
|
403 | }
|
404 |
|
405 | function sendStatus(code, message) {
|
406 | var res = this
|
407 | res.statusCode = code
|
408 | if (code > 199 && code != 204 && code != 304) {
|
409 | res.setHeader("Content-Type", "text/plain")
|
410 | message = (message || statusCodes[code] || code) + "\n"
|
411 | res.setHeader("Content-Length", message.length)
|
412 | if ("HEAD" != res.req.method) {
|
413 | res.write(message)
|
414 | }
|
415 | }
|
416 | res.end()
|
417 | }
|
418 |
|
419 | function sendError(res, opts, e) {
|
420 | var message = typeof e === "string" ? e : e.message
|
421 | , map = opts.errors && (opts.errors[message] || opts.errors[e.name]) || empty
|
422 | , error = {
|
423 | id: util.rand(16),
|
424 | time: res.req.date,
|
425 | code: map.code || e.code || 500,
|
426 | message: map.message || message
|
427 | }
|
428 | res.statusCode = error.code
|
429 | res.statusMessage = statusCodes[error.code] || message
|
430 |
|
431 | res.send(error)
|
432 |
|
433 | ;(opts.errorLog || console.error)(
|
434 | (e.stack || (e.name || "Error") + ": " + error.message).replace(":", ":" + error.id)
|
435 | )
|
436 | }
|
437 |
|
438 | function readBody(req, res, next, opts) {
|
439 | if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
|
440 | req.content(next)
|
441 | } else {
|
442 | next()
|
443 | }
|
444 | }
|
445 |
|
446 | function setLink(url, rel) {
|
447 | var res = this
|
448 | , existing = (res._headers || {})["link"] || []
|
449 |
|
450 | if (!Array.isArray(existing)) {
|
451 | existing = [ existing ]
|
452 | }
|
453 |
|
454 | existing.push('<' + encodeURI(url) + '>; rel="' + rel + '"')
|
455 |
|
456 | res.setHeader("Link", existing)
|
457 | }
|
458 |
|
459 |
|