File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -69,4 +69,14 @@ describe('API — post()', () => {
6969 const api = new API ( '/letter_templates' , 'v1' )
7070 await expect ( api . post ( '/render' , { } ) ) . rejects . toThrow ( APIError )
7171 } )
72+
73+ test ( 'APIError carries HTTP status' , async ( ) => {
74+ axios . post . mockRejectedValue ( {
75+ message : 'Server error' ,
76+ response : { status : 500 }
77+ } )
78+
79+ const api = new API ( '/letter_templates' , 'v1' )
80+ await expect ( api . post ( '/render' , { } ) ) . rejects . toMatchObject ( { status : 500 } )
81+ } )
7282} )
Original file line number Diff line number Diff line change 1+ import axios from 'axios'
2+
3+ export class APIError extends Error {
4+ constructor ( message , status ) {
5+ super ( message )
6+ this . name = 'APIError'
7+ this . status = status
8+ }
9+ }
10+
11+ export class API {
12+ constructor ( path , version ) {
13+ this . baseUrl = version ? `/api/${ version } ${ path } ` : `/api${ path } `
14+ }
15+
16+ async get ( endpoint = '' , params = { } ) {
17+ try {
18+ const res = await axios . get ( this . baseUrl + endpoint , { params } )
19+ return res . data
20+ } catch ( e ) {
21+ throw new APIError ( e . message , e . response ?. status )
22+ }
23+ }
24+
25+ async post ( endpoint = '' , data = { } ) {
26+ try {
27+ const res = await axios . post ( this . baseUrl + endpoint , data )
28+ return res . data
29+ } catch ( e ) {
30+ throw new APIError ( e . message , e . response ?. status )
31+ }
32+ }
33+
34+ async put ( endpoint = '' , data = { } ) {
35+ try {
36+ const res = await axios . put ( this . baseUrl + endpoint , data )
37+ return res . data
38+ } catch ( e ) {
39+ throw new APIError ( e . message , e . response ?. status )
40+ }
41+ }
42+
43+ async delete ( endpoint = '' ) {
44+ try {
45+ const res = await axios . delete ( this . baseUrl + endpoint )
46+ return res . data
47+ } catch ( e ) {
48+ throw new APIError ( e . message , e . response ?. status )
49+ }
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments