@@ -19,24 +19,25 @@ import { ADMIN_SESSION_KEY } from '../modules/common';
1919/**
2020 * Convenience function for sending/receiving JSON for API calls.
2121 */
22- export function reqJSON ( url : string , obj ?: any , method : string = 'POST' ) {
22+ export async function reqJSON ( url : string , obj ?: any , method : string = 'POST' ) {
2323 const body = obj != null ? JSON . stringify ( obj ) : undefined ;
24- return fetchAuth ( url , {
24+ const response = await fetchAuth ( url , {
2525 method,
2626 headers : {
2727 'Accept' : 'application/json' ,
2828 'Content-Type' : 'application/json' ,
2929 } ,
3030 body,
31- } ) . then ( ( response ) => response . json ( ) ) ;
31+ } ) ;
32+ return await response . json ( ) ;
3233}
3334
3435/**
3536 * A wrapper around fetch() to inject an authorization token.
3637 *
3738 * Will throw on non 2xx responses.
3839 */
39- export function fetchAuth ( url : string , options ?: any ) {
40+ export async function fetchAuth ( url : string , options ?: any ) {
4041 options = options || { } ;
4142 const headers = options . headers || { } ;
4243
@@ -45,28 +46,28 @@ export function fetchAuth(url: string, options?: any) {
4546 headers [ 'X-Admin' ] = '1' ;
4647 }
4748
48- return fetch ( url , {
49+ const response = await fetch ( url , {
4950 ...options ,
5051 headers,
5152 credentials : 'same-origin' ,
52- } ) . then ( async ( response ) => {
53- if ( response . ok ) {
54- return response ;
55- } else {
56- let error ;
53+ } ) ;
5754
58- // try to parse as json
59- try {
60- const json = await response . json ( ) ;
61- error = new Error ( json . error ) ;
62- } catch ( ex ) {
63- // otherwise just use the HTTP status code
64- error = new Error ( response . statusText ) ;
65- }
55+ if ( response . ok ) {
56+ return response ;
57+ } else {
58+ let error ;
6659
67- error . code = response . status ;
68- error . response = response ;
69- throw error ;
60+ // try to parse as json
61+ try {
62+ const json = await response . json ( ) ;
63+ error = new Error ( json . error ) ;
64+ } catch ( ex ) {
65+ // otherwise just use the HTTP status code
66+ error = new Error ( response . statusText ) ;
7067 }
71- } ) ;
68+
69+ error . code = response . status ;
70+ error . response = response ;
71+ throw error ;
72+ }
7273}
0 commit comments