Add support for parsing JSON bodies
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Garrett Mills 2021-04-10 05:09:32 -05:00
parent adf21e67ef
commit aca4c8aa4d
Signed by: garrettmills
GPG Key ID: D2BF5FBA8298F246

View File

@ -30,8 +30,51 @@ export class ParseIncomingBodyHTTPModule extends HTTPKernelModule {
protected readonly logging!: Logging
public async apply(request: Request): Promise<Request> {
if ( !request.getHeader('content-type') ) return request
const contentType = request.getHeader('content-type')
const contentTypes = (Array.isArray(contentType) ? contentType : [contentType])
.filter(Boolean).map(x => x!.toLowerCase())
if ( !contentType ) return request
if (
contentTypes.includes('multipart/form-data')
|| contentTypes.includes('application/x-www-form-urlencoded')
) {
return this.applyBusboy(request)
}
if ( contentTypes.includes('application/json') ) {
return this.applyJSON(request)
}
return request
}
public async applyJSON(request: Request): Promise<Request> {
await new Promise<void>((res, rej) => {
let data = ''
request.toNative().on('data', chunk => {
data += chunk
})
request.toNative().on('end', () => {
try {
const body = JSON.parse(data)
for ( const key in body ) {
if ( !body.hasOwnProperty(key) ) continue
request.parsedInput[key] = body[key]
}
res()
} catch (e) {
rej(e)
}
})
})
return request
}
public async applyBusboy(request: Request): Promise<Request> {
const config = this.config.get('server.uploads', {})
await new Promise<void>((res, rej) => {