1- import fetch from 'node-fetch '
1+ import axios from 'axios '
22
33let headers = {
44 'Content-Type' : 'application/json' ,
@@ -9,39 +9,82 @@ export default {
99 async get (
1010 url : string ,
1111 subscriptionKey : string ) {
12- setSubscriptionKey ( subscriptionKey )
13- const response = await fetch ( url , { method : 'GET' , headers} )
14- return response . json ( )
12+ const resp = await httpRequest (
13+ subscriptionKey ,
14+ {
15+ method : 'GET' ,
16+ url,
17+ headers
18+ } )
19+
20+ return resp . data
21+
1522 } ,
1623
1724 async post (
1825 url : string ,
1926 subscriptionKey : string ,
2027 body : any ,
2128 extraHeaders = { } ) {
22- setSubscriptionKey ( subscriptionKey )
2329 headers = { ...headers , ...extraHeaders }
24- const response = await fetch ( url , { method : 'POST' , headers, body : JSON . stringify ( body ) } )
25- return response . json ( )
30+
31+ const resp = await httpRequest (
32+ subscriptionKey ,
33+ {
34+ method : 'POST' ,
35+ url,
36+ data : body ,
37+ headers
38+ } )
39+
40+ return resp . data
2641 } ,
2742
2843 async put (
2944 url : string ,
3045 subscriptionKey : string ,
3146 body : any ) {
32- setSubscriptionKey ( subscriptionKey )
33- const response = await fetch ( url , { method : 'PUT' , headers, body : JSON . stringify ( body ) } )
47+ const resp = await httpRequest (
48+ subscriptionKey ,
49+ {
50+ method : 'PUT' ,
51+ url,
52+ data : body ,
53+ headers
54+ } )
3455
35- return isJSON ( response ) ? response . json ( ) : { code : 'Success' }
56+ return isJSON ( resp . data ) ? resp . data : { code : 'Success' }
3657 } ,
3758
3859 async delete (
3960 url : string ,
4061 subscriptionKey : string ) {
41- setSubscriptionKey ( subscriptionKey )
42- const response = await fetch ( url , { method : 'DELETE' , headers} )
43- return isJSON ( response ) ? response . json ( ) : { code : 'Success' }
62+ const resp = await httpRequest (
63+ subscriptionKey ,
64+ {
65+ method : 'DELETE' ,
66+ url,
67+ headers
68+ } )
69+ return isJSON ( resp . data ) ? resp . data : { code : 'Success' }
70+ }
71+ }
72+
73+ const httpRequest = async function ( subscriptionKey : string , config : any ) {
74+ setSubscriptionKey ( subscriptionKey )
75+ try {
76+ return await axios ( config )
77+ } catch ( error ) {
78+ if ( error . response ) {
79+ // The request was made and the server responded with a status code
80+ // that falls out of the range of 2xx
81+ throw Error ( error . response . statusText )
82+ } else {
83+ // Something happened in setting up the request that triggered an Error
84+ throw Error ( error . message )
85+ }
4486 }
87+
4588}
4689
4790const setSubscriptionKey = function ( subscriptionKey : string ) {
0 commit comments