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