UNPKG

2.9 kBJavaScriptView Raw
1'use strict'
2
3const validation = require('./validation')
4const validateSchema = validation.validate
5const { hookRunner, hookIterator } = require('./hooks')
6const wrapThenable = require('./wrapThenable')
7
8function handleRequest (err, request, reply) {
9 if (reply.sent === true) return
10 if (err != null) {
11 reply.send(err)
12 return
13 }
14
15 var method = request.raw.method
16 var headers = request.headers
17
18 if (method === 'GET' || method === 'HEAD') {
19 handler(request, reply)
20 return
21 }
22
23 var contentType = headers['content-type']
24
25 if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
26 if (contentType === undefined) {
27 if (
28 headers['transfer-encoding'] === undefined &&
29 (headers['content-length'] === '0' || headers['content-length'] === undefined)
30 ) { // Request has no body to parse
31 handler(request, reply)
32 } else {
33 reply.context.contentTypeParser.run('', handler, request, reply)
34 }
35 } else {
36 reply.context.contentTypeParser.run(contentType, handler, request, reply)
37 }
38 return
39 }
40
41 if (method === 'OPTIONS' || method === 'DELETE') {
42 if (
43 contentType !== undefined &&
44 (
45 headers['transfer-encoding'] !== undefined ||
46 headers['content-length'] !== undefined
47 )
48 ) {
49 reply.context.contentTypeParser.run(contentType, handler, request, reply)
50 } else {
51 handler(request, reply)
52 }
53 return
54 }
55
56 // Return 404 instead of 405 see https://github.com/fastify/fastify/pull/862 for discussion
57 reply.code(404).send(new Error('Not Found'))
58}
59
60function handler (request, reply) {
61 if (reply.context.preValidation !== null) {
62 hookRunner(
63 reply.context.preValidation,
64 hookIterator,
65 request,
66 reply,
67 preValidationCallback
68 )
69 } else {
70 preValidationCallback(null, request, reply)
71 }
72}
73
74function preValidationCallback (err, request, reply) {
75 if (reply.res.finished === true) return
76 if (err != null) {
77 reply.send(err)
78 return
79 }
80
81 var result = validateSchema(reply.context, request)
82 if (result) {
83 if (reply.context.attachValidation === false) {
84 reply.code(400).send(result)
85 return
86 }
87
88 reply.request.validationError = result
89 }
90
91 // preHandler hook
92 if (reply.context.preHandler !== null) {
93 hookRunner(
94 reply.context.preHandler,
95 hookIterator,
96 request,
97 reply,
98 preHandlerCallback
99 )
100 } else {
101 preHandlerCallback(null, request, reply)
102 }
103}
104
105function preHandlerCallback (err, request, reply) {
106 if (reply.res.finished === true) return
107 if (err != null) {
108 reply.send(err)
109 return
110 }
111
112 var result = reply.context.handler(request, reply)
113 if (result && typeof result.then === 'function') {
114 wrapThenable(result, reply)
115 }
116}
117
118module.exports = handleRequest
119module.exports[Symbol.for('internals')] = { handler }