| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import APIError from './exceptions/APIError'; |
| 3 |
|
| 4 |
const v1Prefix = '/image-optimizer/v1'; |
| 5 |
|
| 6 |
class API { |
| 7 |
static async request( { path, data, method = 'POST' } ) { |
| 8 |
try { |
| 9 |
const response = await apiFetch( { |
| 10 |
path, |
| 11 |
method, |
| 12 |
data, |
| 13 |
} ); |
| 14 |
|
| 15 |
if ( ! response.success ) { |
| 16 |
throw new APIError( response.data.message ); |
| 17 |
} |
| 18 |
|
| 19 |
return response.data; |
| 20 |
} catch ( e ) { |
| 21 |
if ( e instanceof APIError ) { |
| 22 |
throw e; |
| 23 |
} else { |
| 24 |
throw new APIError( e.message ); |
| 25 |
} |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
static async optimizeSingleImage( { imageId, reoptimize = false } ) { |
| 30 |
return API.request( { |
| 31 |
path: `${ v1Prefix }/optimize/image`, |
| 32 |
data: { |
| 33 |
imageId, |
| 34 |
reoptimize, |
| 35 |
'image-optimization-optimize-image': window?.imageOptimizerControlSettings?.optimizeSingleImageNonce, |
| 36 |
}, |
| 37 |
} ); |
| 38 |
} |
| 39 |
|
| 40 |
static async restoreSingleImage( imageId ) { |
| 41 |
return API.request( { |
| 42 |
path: `${ v1Prefix }/backups/restore/${ imageId }`, |
| 43 |
data: { |
| 44 |
'image-optimization-restore-single': window?.imageOptimizerControlSettings?.restoreSingleImageNonce, |
| 45 |
}, |
| 46 |
} ); |
| 47 |
} |
| 48 |
|
| 49 |
static async getOptimizationStatus( imageIds ) { |
| 50 |
return API.request( { |
| 51 |
path: `${ v1Prefix }/optimize/status`, |
| 52 |
data: { |
| 53 |
image_ids: imageIds, |
| 54 |
}, |
| 55 |
} ); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
export default API; |
| 60 |
|