woocommerce/packages/js/api-core-tests/data/shared/batch-update.js

47 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-08-23 17:39:03 +00:00
/**
* Shared model for batch updates for a resource.
*
2021-09-07 22:20:44 +00:00
* Note that by default the update endpoint is limited to 100 objects to be created, updated, or deleted.
2021-08-23 17:39:03 +00:00
*
* @param {string} action Batch action. Must be one of: create, update, or delete.
* @param {Array} resources A list of resource objects. For the delete action, this will be a list of IDs.
* @param {Object} payload The batch payload object. Defaults to an empty object.
* @return {Object} The payload to send to the batch endpoint.
2021-08-23 17:39:03 +00:00
*/
const batch = ( action, resources = [], payload = {} ) => {
2021-09-07 22:20:44 +00:00
if ( ! [ 'create', 'update', 'delete' ].includes( action ) ) {
2021-08-23 17:39:03 +00:00
return;
}
2021-09-07 22:20:44 +00:00
if ( resources.length === 0 ) {
return;
2021-08-23 17:39:03 +00:00
}
2021-09-07 22:20:44 +00:00
if ( action === 'create' ) {
payload.create = [ ...resources ];
}
2021-08-23 17:39:03 +00:00
2021-09-07 22:20:44 +00:00
if ( action === 'update' ) {
payload.update = [ ...resources ];
2021-08-23 17:39:03 +00:00
}
2021-09-07 22:20:44 +00:00
if ( action === 'delete' ) {
payload.delete = [ ...resources ];
}
2021-08-23 17:39:03 +00:00
2021-09-07 22:20:44 +00:00
return payload;
};
2021-08-23 17:39:03 +00:00
const getBatchPayloadExample = ( resource ) => {
2021-09-07 22:20:44 +00:00
let batchUpdatePayload = {};
batchUpdatePayload = batch( 'create', [ resource ], batchUpdatePayload );
batchUpdatePayload = batch( 'update', [ resource ], batchUpdatePayload );
batchUpdatePayload = batch( 'delete', [ 1, 2, 3 ], batchUpdatePayload );
2021-08-23 17:39:03 +00:00
return batchUpdatePayload;
2021-09-07 22:20:44 +00:00
};
2021-08-23 17:39:03 +00:00
module.exports = {
2021-09-07 22:20:44 +00:00
batch,
getBatchPayloadExample,
};