forked from jeremydaly/lambda-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.js
More file actions
84 lines (64 loc) · 1.65 KB
/
response.js
File metadata and controls
84 lines (64 loc) · 1.65 KB
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
'use strict'
class RESPONSE {
// Create the constructor function.
constructor(app) {
// Create a local copy of the app
this.app = app
// Default statusCode to 200
this._statusCode = 200
// Default the header
this._headers = {
// Set the Content-Type by default
"Content-Type": "application/json" //charset=UTF-8
}
}
// Sets the statusCode
status(code) {
this._statusCode = code
return this
}
// Adds a header field
header(field,value) {
this._headers[field] = value
return this
}
// Convenience method for JSON
json(body) {
this.header('Content-Type','application/json').send(JSON.stringify(body))
}
// TODO: Convenience method for JSONP
// jsonp(body) {
// this.header('Content-Type','application/json').send(JSON.stringify(body))
// }
// Convenience method for HTML
html(body) {
this.header('Content-Type','text/html').send(body)
}
// TODO: cookie
// TODO: clearCookie
// TODO: attachement
// TODO: download
// TODO: location
// TODO: redirect
// TODO: sendFile
// TODO: sendStatus
// TODO: type
// Sends the request to the main callback
send(body) {
// Create the response
const response = {
headers: this._headers,
statusCode: this._statusCode,
body: typeof body === 'object' ? JSON.stringify(body) : (body && typeof body !== 'string' ? body.toString() : (body ? body : ''))
}
// Trigger the callback function
return this.app._callback(null, response)
} // end send
// Trigger API error
error(err) {
// Reject promise
this.app._reject(err)
} // end error
} // end Response class
// Export the response object
module.exports = RESPONSE