| 1 |
import apiFetch from "@wordpress/api-fetch"; |
| 2 |
|
| 3 |
/** |
| 4 |
* Give QuickBuilder's ajax requests an HTTP method. |
| 5 |
* |
| 6 |
* QuickBuilder's `hitAAJX()` calls `apiFetch({ path, data })` and never passes a |
| 7 |
* method — not even the one the field config declares. `data` makes apiFetch |
| 8 |
* attach a request body, and with no method the browser defaults to GET, so |
| 9 |
* `fetch()` rejects before anything leaves the page: |
| 10 |
* |
| 11 |
* TypeError: Request with GET/HEAD method cannot have body. |
| 12 |
* |
| 13 |
* apiFetch turns that rejection into `{ code: "fetch_error", message: "Could not |
| 14 |
* get a valid response from the server." }` — which reads like a server or |
| 15 |
* network fault while the request was never actually sent. Every QuickBuilder |
| 16 |
* ajax button hits this: the AI Chatbot "Save", report test, import/export. |
| 17 |
* |
| 18 |
* This cannot regress a working request. It only fills in a method where the |
| 19 |
* call throws today, 100% of the time, so there is no success path to break. |
| 20 |
* |
| 21 |
* Scoped to our own namespace ON PURPOSE. Some select fields point `ajax.api` at |
| 22 |
* core routes (`/wp/v2/docs`, `/wp/v2/knowledge_base`) with data and an intended |
| 23 |
* `method: "GET"`; POSTing those would CREATE a post or a term instead of |
| 24 |
* reading a list. Those stay exactly as they are — the real repair for them is |
| 25 |
* teaching `hitAAJX()` to forward `ajax.method` upstream in QuickBuilder. |
| 26 |
*/ |
| 27 |
const registerQuickBuilderFetchFix = () => { |
| 28 |
apiFetch.use( ( options, next ) => { |
| 29 |
const path = options?.path || ""; |
| 30 |
const isOurs = |
| 31 |
path.startsWith( "/betterdocs/" ) || path.startsWith( "betterdocs/" ); |
| 32 |
|
| 33 |
if ( isOurs && options?.data && ! options?.method ) { |
| 34 |
return next( { ...options, method: "POST" } ); |
| 35 |
} |
| 36 |
|
| 37 |
return next( options ); |
| 38 |
} ); |
| 39 |
}; |
| 40 |
|
| 41 |
export default registerQuickBuilderFetchFix; |
| 42 |
|