make loki_message_api::sendMessage use async/await

pull/6/head
sachaaaaa 7 years ago
parent bb65115d7d
commit 8bb7185c7a

@ -19,7 +19,7 @@ function initialize({ url }) {
sendMessage sendMessage
}; };
function sendMessage(pub_key, data, ttl) async function sendMessage(pub_key, data, ttl)
{ {
const options = { const options = {
url: `${url}/send_message`, url: `${url}/send_message`,
@ -28,8 +28,6 @@ function initialize({ url }) {
timeout: undefined timeout: undefined
}; };
return new Promise((resolve, reject) => {
log.info(options.type, options.url); log.info(options.type, options.url);
const body = JSON.stringify({ const body = JSON.stringify({
@ -47,40 +45,38 @@ function initialize({ url }) {
fetchOptions.headers['Content-Type'] = 'application/json; charset=utf-8'; fetchOptions.headers['Content-Type'] = 'application/json; charset=utf-8';
fetch(options.url, fetchOptions) let response;
.then(response => { try {
let resultPromise; response = await fetch(options.url, fetchOptions);
}
catch(e) {
log.error(options.type, options.url, 0, 'Error');
throw HTTPError('fetch error', 0, e.toString());
}
let result;
if ( if (
options.responseType === 'json' && options.responseType === 'json' &&
response.headers.get('Content-Type') === 'application/json' response.headers.get('Content-Type') === 'application/json'
) { ) {
resultPromise = response.json(); result = await response.json();
} else if (options.responseType === 'arraybuffer') { } else if (options.responseType === 'arraybuffer') {
resultPromise = response.buffer(); result = await response.buffer();
} else { } else {
resultPromise = response.text(); result = await response.text();
} }
return resultPromise.then(result => {
if (response.status >= 0 && response.status < 400) { if (response.status >= 0 && response.status < 400) {
log.info(options.type, options.url, response.status, 'Success'); log.info(options.type, options.url, response.status, 'Success');
resolve(result, response.status); return [result, response.status];
} else { } else {
log.error(options.type, options.url, response.status, 'Error'); log.error(options.type, options.url, response.status, 'Error');
reject( throw HTTPError(
HTTPError( 'sendMessage: error response',
'promiseAjax: error response',
response.status, response.status,
result result
)
); );
} }
});
})
.catch(e => {
log.error(options.type, options.url, 0, 'Error');
reject(HTTPError('promiseAjax catch', 0, e.toString()));
});
});
} }
} }
} }

Loading…
Cancel
Save