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

100 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-23 18:10:37 +00:00
import { fetchWithHeaders } from './controls';
import { RegisteredChannel, RecommendedChannel, Campaign } from './types';
import { API_NAMESPACE } from './constants';
import { isApiFetchError } from './guards';
2023-02-23 18:10:37 +00:00
const getIntHeaderValues = (
response: {
headers: Map< string, string >;
data: unknown;
},
keys: string[]
) => {
return keys.map( ( key ) => {
const value = response.headers.get( key );
if ( value === undefined ) {
throw new Error( `'${ key }' header is missing.` );
}
return parseInt( value, 10 );
} );
};
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;
}
}
2023-02-23 18:10:37 +00:00
export function* getCampaigns( page: number, perPage: number ) {
try {
2023-02-23 18:10:37 +00:00
const resp: {
headers: Map< string, string >;
data: Array< Campaign >;
} = yield fetchWithHeaders( {
path: `${ API_NAMESPACE }/campaigns?page=${ page }&per_page=${ perPage }`,
parse: false,
} );
2023-02-23 18:10:37 +00:00
const [ total ] = getIntHeaderValues( resp, [ 'x-wp-total' ] );
yield receiveCampaignsSuccess( {
payload: resp.data,
error: false,
meta: {
page,
perPage,
total,
},
} );
} catch ( error ) {
2023-02-23 18:10:37 +00:00
// TODO: error is an HTTPResponse that hasn't been parsed.
if ( isApiFetchError( error ) ) {
yield receiveCampaignsError( error );
}
throw error;
}
}