1+ import { convert } from 'xmlbuilder2' ;
12import ApiError from './ApiError' ;
23
34/** Process a text response, returning the text as a string */
@@ -17,6 +18,25 @@ export async function text(response: Promise<Response>): Promise<string> {
1718 return text ;
1819}
1920
21+ /** Process an XML response, converting it to a JS object */
22+ export async function xml ( response : Promise < Response > ) : Promise < object > {
23+ // TODO: Fix this coed duplication
24+ const res = await response ;
25+ if ( [ 404 , 405 ] . includes ( res . status ) ) {
26+ throw new ApiError ( 404 , `Error ${ res . status } at ${ res . url } ` ) ;
27+ }
28+ const text = await res . text ( ) ;
29+ if ( [ 400 , 401 , 403 ] . includes ( res . status ) ) {
30+ throw new ApiError ( res . status , text ) ;
31+ }
32+ if ( ! [ 200 , 304 ] . includes ( res . status ) ) {
33+ // Unknown error
34+ throw new ApiError ( res . status , `Request got status code ${ res . status } ` ) ;
35+ }
36+
37+ return convert ( text , { format : 'object' } ) ;
38+ }
39+
2040/** Process a JSON response, returning the data as a JS object */
2141export async function json ( response : Promise < Response > ) : Promise < object > {
2242 const res = await response ;
@@ -81,6 +101,7 @@ export async function buffer(response: Promise<Response>): Promise<Uint8Array> {
81101 */
82102export default ( response : Promise < Response > ) => ( {
83103 json : ( ) => json ( response ) ,
104+ xml : ( ) => xml ( response ) ,
84105 text : ( ) => text ( response ) ,
85106 buffer : ( ) => buffer ( response ) ,
86107 response,
0 commit comments