Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 1x 10x 2x 10x 2x 10x 10x 10x 10x 1x 10x 10x 10x 1x 10x 10x 10x 10x 2x 2x 18x 2x 2x 18x 2x 2x 1x 1x 16x 2x 2x 2x 1x 1x 7x 6x 6x 7x 7x 7x 7x 7x 7x 2x 1x 1x 1x 7x 7x 7x 7x 16x 17x 17x 17x 17x 4x 4x 13x 13x 13x 13x 13x 1x 1x 6x 6x 6x 1x 5x 1x 4x 2x 2x 4x 4x 4x 104x 104x 2x 2x 17x 17x 1x 1x 16x 16x 16x 4x 12x 10x 50x 50x 13x 13x 8x 8x 13x 15x 1x 12x 12x 12x 12x 12x 12x 13x 2x 2x 1x 1x 13x 13x 13x 1x 1x | const http = require('http')
const https = require('https')
const querystring = require('querystring')
const Buffer = require('buffer').Buffer
const stringify = require('fast-safe-stringify')
const wayfarer = require('wayfarer')
const concat = require('concat-stream')
const methods = ['get', 'put', 'post', 'delete', 'patch']
const dataMethods = ['put', 'post', 'patch']
const MAX_POST = 512 * 1024
const ORIGIN = '*'
const CREDENTIALS = true
const HEADERS = ['Content-Type', 'Accept', 'X-Requested-With']
class TakeFive {
constructor (opts) {
this._allowMethods = ['options'].concat(methods)
this._allowHeaders = HEADERS.slice(0)
opts = opts || {}
this.maxPost = opts.maxPost || MAX_POST
this.allowOrigin = opts.allowOrigin || ORIGIN
this.allowCredentials = CREDENTIALS
if (typeof opts.allowCredentials === 'boolean') {
this.allowCredentials = opts.allowCredentials
}
if (opts.allowHeaders) {
this.allowHeaders = opts.allowHeaders
}
if (opts.allowMethods) {
this.allowMethods = opts.allowMethods
}
this._httpLib = http
this._httpOpts = opts.http || {}
this._ctx = {}
if (this._httpOpts.key && this._httpOpts.cert) {
this._httpLib = https
}
this.routers = new Map()
const args = []
if (Object.keys(this._httpOpts).length > 0) {
args.push(this._httpOpts)
}
args.push(this._onRequest.bind(this))
this.server = this._httpLib.createServer.apply(this._httpLib, args)
this.methods = methods.concat(opts.methods || [])
this._addRouters()
}
set allowHeaders (headers) {
headers = Array.isArray(headers) ? headers : [headers]
this._allowHeaders = this._allowHeaders.concat(headers)
}
get allowHeaders () {
return this._allowHeaders
}
set allowMethods (methods) {
methods = Array.isArray(methods) ? methods : [methods]
this._allowMethods = this._allowMethods.concat(methods)
}
get allowMethods () {
return this._allowMethods
}
set ctx (ctx) {
const ctxType = Object.prototype.toString.call(ctx)
if (ctxType !== '[object Object]') {
throw new Error(`ctx must be an object, was ${ctxType}`)
}
this._ctx = Object.assign({}, ctx)
}
get ctx () {
return this._ctx
}
parseBody (req, res, ctx) {
Eif (!res.finished) {
try {
ctx.body = JSON.parse(ctx.body)
this._handleRequest(req, res, ctx)
} catch (err) {
return ctx.err(400, 'Payload is not valid JSON')
}
}
}
makeCtx (res) {
function send (code, content) {
if (typeof content === 'undefined') {
content = code
code = 200
}
Eif (typeof content !== 'string') {
content = stringify(content)
}
res.statusCode = code
res.setHeader('content-type', 'application/json')
res.end(content, 'utf8')
}
function err (code, content) {
if (typeof content === 'undefined') {
if (parseInt(code, 10)) {
content = http.STATUS_CODES[code]
} else {
content = code
code = 500
}
}
res.statusCode = code
res.statusMessage = content
res.setHeader('content-type', 'application/json')
res.end(stringify({message: content}))
}
return Object.assign({}, this.ctx, {send, err})
}
handleError (err, req, res, ctx) { // eslint-disable-line
}
cors (res) {
res.setHeader('Access-Control-Allow-Origin', this.allowOrigin)
res.setHeader('Access-Control-Allow-Headers', this.allowHeaders.join(','))
res.setHeader('Access-Control-Allow-Credentials', this.allowCredentials)
res.setHeader('Access-Control-Allow-Methods', this.allowMethods.join(',').toUpperCase())
}
listen (port, func) {
this.server.listen(port, func)
}
close () {
this.server.close()
}
_handleRequest (req, res, ctx) {
try {
const method = req.method.toLowerCase()
const url = req.url.split('?')[0]
const router = this.routers.get(method)
router(url, req, res, ctx)
} catch (err) {
Iif (res.finished) {
throw err
}
return ctx.err(404, 'Not found')
}
}
_verifyBody (req, res, ctx) {
const type = req.headers['content-type']
const size = req.headers['content-length']
if (size > this.maxPost) {
return ctx.err(413, `Payload size exceeds maximum size for requests`)
}
if (type !== 'application/json') {
return ctx.err(415, `POST requests must be application/json not ${type}`)
} else {
const parser = concat((data) => {
ctx.body = data.toString('utf8')
this.parseBody(req, res, ctx)
})
req.pipe(parser)
const body = []
req.on('data', (chunk) => {
body.push(chunk.toString('utf8'))
if (chunk.length > this.maxPost || Buffer.byteLength(body.join(''), 'utf8') > this.maxPost) {
req.pause()
return ctx.err(413, 'Payload size exceeds maximum body length')
}
})
}
}
_onRequest (req, res) {
this.cors(res)
if (req.method === 'OPTIONS') {
res.statusCode = 204
return res.end()
}
const ctx = this.makeCtx(res)
const conlen = parseInt(req.headers['content-length'], 10) || 0
if (conlen !== 0 && dataMethods.includes(req.method.toLowerCase())) {
this._verifyBody(req, res, ctx)
} else {
this._handleRequest(req, res, ctx)
}
}
_addRouters () {
this.methods.forEach((method) => {
Object.defineProperty(this, method, {value: generateRouter(method)})
})
function generateRouter (method) {
return function (matcher, handler) {
let router = this.routers.get(method)
if (!router) {
router = wayfarer('/_')
this.routers.set(method, router)
}
const handlers = Array.isArray(handler) ? handler : [handler]
if (handlers.some((f) => typeof f !== 'function')) {
throw new Error('handlers must be functions')
}
router.on(matcher, (params, req, res, ctx) => {
ctx.query = querystring.parse(req.url.split('?')[1])
ctx.params = params
this._resolveHandlers(req, res, ctx, handlers.slice(0))
})
}
}
}
_resolveHandlers (req, res, ctx, handlers) {
const next = handlers.shift()
iterate(next)
function iterate (handler) {
const done = (value) => {
Iif (value instanceof Error) {
return this.handleError(value, req, res, ctx)
}
if (!res.finished && handlers.length > 0) {
const next = handlers.shift()
iterate(next)
}
}
ctx.next = done
const handlerPromise = handler(req, res, ctx)
if (handlerPromise && typeof handlerPromise.then === 'function') {
handlerPromise
.then(done)
.catch((err) => {
this.handleError(err, req, res, ctx)
})
}
}
}
}
module.exports = TakeFive
|