File size: 2,257 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
import i18n from 'i18n-calypso';
import {
	JETPACK_CREDENTIALS_AUTOCONFIGURE,
	JETPACK_CREDENTIALS_STORE,
	REWIND_STATE_UPDATE,
} from 'calypso/state/action-types';
import { registerHandlers } from 'calypso/state/data-layer/handler-registry';
import { transformApi } from 'calypso/state/data-layer/wpcom/sites/rewind/api-transformer';
import { http } from 'calypso/state/data-layer/wpcom-http/actions';
import { dispatchRequest } from 'calypso/state/data-layer/wpcom-http/utils';
import { successNotice, errorNotice } from 'calypso/state/notices/actions';
import { requestRewindState } from 'calypso/state/rewind/state/actions';

export const fetch = ( action ) => {
	const notice = successNotice( i18n.translate( 'Obtaining your credentials…' ) );
	const {
		notice: { noticeId },
	} = notice;

	return [
		notice,
		http(
			{
				apiVersion: '1.1',
				method: 'POST',
				path: `/activity-log/${ action.siteId }/rewind/activate`,
			},
			{ ...action, noticeId }
		),
	];
};

export const storeAndAnnounce = ( { siteId, noticeId }, { rewind_state } ) => [
	{
		type: JETPACK_CREDENTIALS_STORE,
		credentials: { main: { type: 'auto' } }, // fake for now until data actually comes through
		siteId,
	},

	successNotice( i18n.translate( 'Your credentials have been auto configured.' ), {
		duration: 4000,
		id: noticeId,
	} ),
	// right now the `/activate` endpoint returns before the
	// server realizes we're now in the 'active' state so we
	// need to make the additional update here to clear that up
	requestRewindState( siteId ),
	// the API transform could fail and the rewind data might
	// be unavailable so if that's the case just let it go
	// for now. we'll improve our rigor as time goes by.
	() => {
		try {
			return {
				type: REWIND_STATE_UPDATE,
				siteId,
				data: transformApi( rewind_state ),
			};
		} catch ( e ) {}
	},
];

export const announceFailure = ( { noticeId } ) =>
	errorNotice( i18n.translate( 'Error auto configuring your credentials.' ), {
		duration: 4000,
		id: noticeId,
	} );

registerHandlers( 'state/data-layer/wpcom/activity-log/rewind/activate/index.js', {
	[ JETPACK_CREDENTIALS_AUTOCONFIGURE ]: [
		dispatchRequest( {
			fetch,
			onSuccess: storeAndAnnounce,
			onError: announceFailure,
		} ),
	],
} );