-
Notifications
You must be signed in to change notification settings - Fork 2k
/
utils.js
54 lines (40 loc) · 1.28 KB
/
utils.js
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
/** @format */
/**
* External dependencies
*/
import { Component } from 'react';
import { isEmpty } from 'lodash';
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import { debugMiddleware, wpcomProxyMiddleware, wpcomPathMappingMiddleware } from './index';
export class WithAPIMiddleware extends Component {
state = { hasMiddleware: false };
componentDidMount() {
const { siteSlug } = this.props;
if ( ! isEmpty( siteSlug ) ) {
this.applyAPIMiddleware( siteSlug );
}
}
componentDidUpdate() {
const { siteSlug } = this.props;
const { hasMiddleware } = this.state;
if ( hasMiddleware || isEmpty( siteSlug ) ) {
return;
}
this.applyAPIMiddleware( siteSlug );
}
applyAPIMiddleware = siteSlug => {
// First middleware in, last out.
// This call intentionally breaks the middleware chain.
apiFetch.use( options => wpcomProxyMiddleware( options ) );
apiFetch.use( ( options, next ) => debugMiddleware( options, next ) );
apiFetch.use( ( options, next ) => wpcomPathMappingMiddleware( options, next, siteSlug ) );
apiFetch.use( apiFetch.createRootURLMiddleware( 'https://public-api.wordpress.com/' ) );
this.setState( { hasMiddleware: true } );
};
render() {
return this.state.hasMiddleware ? this.props.children : null;
}
}