File size: 1,900 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
import { map, mapValues } from 'lodash';
import { TIMEZONES_REQUEST } from 'calypso/state/action-types';
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';
import { timezonesReceive } from 'calypso/state/timezones/actions';

const noop = () => {};

/**
 * Converts an value/label pairs from API into object whose
 * keys are the values and whose values are the labels.
 * @example
 * valueLabelToObject( [ { value: 'foo', label: 'bar' }, { value: 'biz', label: 'bat' } ] )
 * // returns { foo: 'bar', biz: 'bat' }
 * @param {Array} pairs - timezone values and display labels
 * @returns {Object} object whose keys are timezone values, values are timezone labels
 */
const timezonePairsToMap = ( pairs ) =>
	Object.fromEntries( map( pairs, ( { label, value } ) => [ value, label ] ) );

/**
 * Normalize data gotten from the REST API making them more Calypso friendly.
 * @returns {Object} normalized timezones data.
 */
export const fromApi = ( { manual_utc_offsets, timezones, timezones_by_continent } ) => ( {
	rawOffsets: timezonePairsToMap( manual_utc_offsets ),
	labels: timezonePairsToMap( timezones ),
	byContinents: mapValues( timezones_by_continent, ( zones ) =>
		map( zones, ( { value } ) => value )
	),
} );

/*
 * Start a request to WordPress.com server to get the timezones data
 */
export const fetchTimezones = ( action ) =>
	http(
		{
			method: 'GET',
			path: '/timezones',
			apiNamespace: 'wpcom/v2',
		},
		action
	);

export const addTimezones = ( action, data ) => timezonesReceive( data );

registerHandlers( 'state/data-layer/wpcom/timezones/index.js', {
	[ TIMEZONES_REQUEST ]: [
		dispatchRequest( {
			fetch: fetchTimezones,
			onSuccess: addTimezones,
			onError: noop,
			fromApi,
		} ),
	],
} );