File size: 3,365 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { extendAction } from '@automattic/state-utils';
import debugModule from 'debug';
import { get } from 'lodash';
import wpcom, { wpcomJetpackLicensing } from 'calypso/lib/wp';
import { WPCOM_HTTP_REQUEST } from 'calypso/state/action-types';
import {
	processInbound as inboundProcessor,
	processOutbound as outboundProcessor,
} from './pipeline';

const debug = debugModule( 'calypso:data-layer:wpcom-http' );

/**
 * Returns the appropriate fetcher in wpcom given the request method
 *
 * fetcherMap :: String -> (Params -> Query -> [Body] -> Promise)
 * @param {string} method name of HTTP method for request
 * @param {string} fetcher Name of fetcher to use. Defaults to wpcom.
 * @returns {Function} the fetcher
 */
const fetcherMap = function ( method, fetcher = 'wpcom' ) {
	const req = 'wpcomJetpackLicensing' === fetcher ? wpcomJetpackLicensing.req : wpcom.req;

	return get(
		{
			GET: req.get.bind( req ),
			POST: req.post.bind( req ),
		},
		method,
		null
	);
};

export const successMeta = ( data, headers ) => ( { meta: { dataLayer: { data, headers } } } );
export const failureMeta = ( error, headers ) => ( { meta: { dataLayer: { error, headers } } } );
export const progressMeta = ( { total, loaded } ) => ( {
	meta: { dataLayer: { progress: { total, loaded } } },
} );
export const streamRecordMeta = ( streamRecord ) => ( { meta: { dataLayer: { streamRecord } } } );

export const queueRequest =
	( processOutbound, processInbound ) =>
	( { dispatch }, rawAction ) => {
		const action = processOutbound( rawAction, dispatch );

		if ( null === action ) {
			return;
		}

		const {
			body,
			formData,
			onStreamRecord: rawOnStreamRecord,
			method: rawMethod,
			onProgress,
			options,
			path,
			query = {},
		} = action;
		const { responseType, isLocalApiCall } = options || {};
		const fetcher = get( options, 'options.fetcher', 'wpcom' );

		const onStreamRecord =
			rawOnStreamRecord &&
			( ( record ) => {
				return dispatch( extendAction( rawOnStreamRecord, streamRecordMeta( record ) ) );
			} );

		const method = rawMethod.toUpperCase();

		const request = fetcherMap(
			method,
			fetcher
		)(
			...[
				{ path, formData, onStreamRecord, responseType, isLocalApiCall },
				{ ...query }, // wpcom mutates the query so hand it a copy
				method === 'POST' && body,
				( error, data, headers ) => {
					debug( 'callback fn by Req method: error=%o data=%o headers=%o', error, data, headers );

					const { failures, nextData, nextError, nextHeaders, shouldAbort, successes } =
						processInbound( action, { dispatch }, data, error, headers );

					if ( true === shouldAbort ) {
						return null;
					}

					return nextError
						? failures.forEach( ( handler ) =>
								dispatch( extendAction( handler, failureMeta( nextError, nextHeaders ) ) )
						  )
						: successes.forEach( ( handler ) =>
								dispatch( extendAction( handler, successMeta( nextData, nextHeaders ) ) )
						  );
				},
			].filter( Boolean )
		);

		if ( 'POST' === method && onProgress ) {
			// wpcomProxyRequest request - wpcomXhrRequests come through here with .upload
			if ( request.upload ) {
				request.upload.onprogress = ( event ) =>
					dispatch( extendAction( onProgress, progressMeta( event ) ) );
			}
		}
	};

export default {
	[ WPCOM_HTTP_REQUEST ]: [ queueRequest( outboundProcessor, inboundProcessor ) ],
};