fix(core): update

This commit is contained in:
Philipp Kunz 2019-06-12 15:16:27 +02:00
parent fe693e6383
commit 74b6bf230f
2 changed files with 21 additions and 5 deletions

View File

@ -3,4 +3,5 @@ import * as https from 'https';
export interface ISmartRequestOptions extends https.RequestOptions { export interface ISmartRequestOptions extends https.RequestOptions {
requestBody?: any; requestBody?: any;
autoJsonParse?: boolean;
} }

View File

@ -9,7 +9,8 @@ export interface IExtendedIncomingMessage extends IncomingMessage {
} }
const buildUtf8Response = ( const buildUtf8Response = (
incomingMessageArg: IncomingMessage incomingMessageArg: IncomingMessage,
autoJsonParse = true
): Promise<IExtendedIncomingMessage> => { ): Promise<IExtendedIncomingMessage> => {
let done = plugins.smartpromise.defer<IExtendedIncomingMessage>(); let done = plugins.smartpromise.defer<IExtendedIncomingMessage>();
// Continuously update stream with data // Continuously update stream with data
@ -19,11 +20,15 @@ const buildUtf8Response = (
}); });
incomingMessageArg.on('end', function() { incomingMessageArg.on('end', function() {
if (autoJsonParse) {
try { try {
(incomingMessageArg as IExtendedIncomingMessage).body = JSON.parse(body); (incomingMessageArg as IExtendedIncomingMessage).body = JSON.parse(body);
} catch (err) { } catch (err) {
(incomingMessageArg as IExtendedIncomingMessage).body = body; (incomingMessageArg as IExtendedIncomingMessage).body = body;
} }
} else {
(incomingMessageArg as IExtendedIncomingMessage).body = body;
}
done.resolve(incomingMessageArg as IExtendedIncomingMessage); done.resolve(incomingMessageArg as IExtendedIncomingMessage);
}); });
return done.promise; return done.promise;
@ -57,6 +62,16 @@ export let request = async (
): Promise<IExtendedIncomingMessage> => { ): Promise<IExtendedIncomingMessage> => {
let done = plugins.smartpromise.defer<any>(); let done = plugins.smartpromise.defer<any>();
// merge options
const defaultOptions: interfaces.ISmartRequestOptions = {
autoJsonParse: true
}
optionsArg = {
...defaultOptions,
...optionsArg
}
// parse url // parse url
let parsedUrl: plugins.url.Url; let parsedUrl: plugins.url.Url;
parsedUrl = plugins.url.parse(domainArg); parsedUrl = plugins.url.parse(domainArg);
@ -114,7 +129,7 @@ export let request = async (
if (streamArg) { if (streamArg) {
done.resolve(response); done.resolve(response);
} else { } else {
const builtResponse = await buildUtf8Response(response); const builtResponse = await buildUtf8Response(response, optionsArg.autoJsonParse);
done.resolve(builtResponse); done.resolve(builtResponse);
} }
}); });