| | |
| | | */ |
| | | async fetch(url, options = {}) { |
| | | const attempt = async (retryCount = 0) => { |
| | | const isFormData = options.body instanceof FormData; |
| | | |
| | | const headers = { |
| | | 'Content-Type': 'application/json', |
| | | ...(!isFormData && { 'Content-Type': 'application/json' }), |
| | | ...options.headers, |
| | | 'X-WP-Nonce': this.getNonce() |
| | | }; |
| | |
| | | if (result.code === 'rest_cookie_invalid_nonce' || result.message?.includes('Cookie check')) { |
| | | console.log('Nonce invalid, refreshing auth...'); |
| | | await this.refresh(); |
| | | return attempt(1); |
| | | return attempt(retryCount + 1); |
| | | } |
| | | } |
| | | |
| | |
| | | * Set authentication data |
| | | */ |
| | | setAuthData(authData) { |
| | | const wasAuthenticated = this.initialized && this.authenticated; |
| | | |
| | | this.authenticated = authData.authenticated || false; |
| | | this.user = authData.user || false; |
| | | this.nonces = authData.nonces || {}; |
| | | |
| | | // Session expired — was logged in, now isn't |
| | | if (wasAuthenticated && !this.authenticated) { |
| | | window.location.href = `/login?redirect_to=${encodeURIComponent(window.location.href)}`; |
| | | } |
| | | } |
| | | |
| | | /** |