File size: 2,032 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { ATOMIC_TRANSFER_INITIATE_TRANSFER } from 'calypso/state/action-types';
import { recordTracksEvent } from 'calypso/state/analytics/actions';
import {
	setLatestAtomicTransfer,
	setLatestAtomicTransferError,
} from 'calypso/state/atomic/transfers/actions';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';

export const mapToRequestBody = ( action ) => {
	const requestBody = {};

	if ( action.softwareSet ) {
		requestBody.software_set = action.softwareSet;
	}

	if ( action.themeSlug ) {
		requestBody.theme_slug = action.themeSlug;
	}

	if ( action.pluginSlug ) {
		requestBody.plugin_slug = action.pluginSlug;
	}

	if ( action.themeFile ) {
		requestBody.theme_file = action.themeFile;
	}

	if ( action.pluginFile ) {
		requestBody.plugin_file = action.pluginFile;
	}

	if ( action.context ) {
		requestBody.context = action.context;
	}

	if ( action.transferIntent ) {
		requestBody.transfer_intent = action.transferIntent;
	}

	return requestBody;
};

const initiateAtomicTransfer = ( action ) =>
	http(
		{
			apiNamespace: 'wpcom/v2',
			method: 'POST',
			path: `/sites/${ action.siteId }/atomic/transfers/`,
			body: mapToRequestBody( action ),
		},
		action
	);

const receiveResponse = ( action, transfer ) => [
	recordTracksEvent( 'calypso_atomic_transfer_inititate_success', {
		context: 'atomic_transfer',
	} ),
	setLatestAtomicTransfer( action.siteId, transfer ),
];

const receiveError = ( action, error ) => [
	recordTracksEvent( 'calypso_atomic_transfer_inititate_failure', {
		context: 'atomic_transfer',
		error: error.error,
	} ),
	setLatestAtomicTransferError( action.siteId, error ),
];

registerHandlers( 'state/data-layer/wpcom/sites/atomic/transfers', {
	[ ATOMIC_TRANSFER_INITIATE_TRANSFER ]: [
		dispatchRequest( {
			fetch: initiateAtomicTransfer,
			onSuccess: receiveResponse,
			onError: receiveError,
		} ),
	],
} );