woocommerce/plugins/woocommerce-admin/client/marketing/data-multichannel/resolvers.ts

103 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* External dependencies
*/
import { apiFetch } from '@wordpress/data-controls';
/**
* Internal dependencies
*/
2023-01-19 11:33:51 +00:00
import {
receiveRegisteredChannelsSuccess,
receiveRegisteredChannelsError,
2023-01-19 11:33:51 +00:00
receiveRecommendedChannelsSuccess,
receiveRecommendedChannelsError,
receiveCampaignsSuccess,
receiveCampaignsError,
2023-01-19 11:33:51 +00:00
} from './actions';
2023-02-24 10:32:33 +00:00
import { awaitResponseJson } from './controls';
import {
RegisteredChannel,
RecommendedChannel,
Campaign,
ApiFetchError,
} from './types';
import { API_NAMESPACE } from './constants';
import { isApiFetchError } from './guards';
export function* getRegisteredChannels() {
try {
const data: RegisteredChannel[] = yield apiFetch( {
path: `${ API_NAMESPACE }/channels`,
} );
yield receiveRegisteredChannelsSuccess( data );
} catch ( error ) {
if ( isApiFetchError( error ) ) {
yield receiveRegisteredChannelsError( error );
}
throw error;
}
}
2023-01-19 11:33:51 +00:00
export function* getRecommendedChannels() {
try {
2023-01-20 18:14:36 +00:00
const data: RecommendedChannel[] = yield apiFetch( {
2023-01-19 11:33:51 +00:00
path: `${ API_NAMESPACE }/recommendations?category=channels`,
} );
yield receiveRecommendedChannelsSuccess( data );
} catch ( error ) {
if ( isApiFetchError( error ) ) {
yield receiveRecommendedChannelsError( error );
}
throw error;
}
}
const getTotalFromResponse = ( response: Response ) => {
return (
parseInt( response.headers.get( 'x-wp-total' ) || '0', 10 ) || undefined
);
};
2023-02-23 18:10:37 +00:00
export function* getCampaigns( page: number, perPage: number ) {
try {
2023-02-24 10:32:33 +00:00
const response: Response = yield apiFetch( {
2023-02-23 18:10:37 +00:00
path: `${ API_NAMESPACE }/campaigns?page=${ page }&per_page=${ perPage }`,
parse: false,
} );
const total = getTotalFromResponse( response );
2023-02-24 10:32:33 +00:00
const payload: Campaign[] = yield awaitResponseJson( response );
2023-02-23 18:10:37 +00:00
yield receiveCampaignsSuccess( {
2023-02-24 10:32:33 +00:00
payload,
2023-02-23 18:10:37 +00:00
error: false,
meta: {
page,
perPage,
total,
},
} );
} catch ( error ) {
2023-02-24 10:32:33 +00:00
if ( error instanceof Response ) {
const total = getTotalFromResponse( error );
2023-02-24 10:32:33 +00:00
const payload: ApiFetchError = yield awaitResponseJson( error );
yield receiveCampaignsError( {
payload,
error: true,
meta: {
page,
perPage,
total,
},
} );
}
throw error;
}
}