Skip to content

Commit 7c17a05

Browse files
committed
Add a section about infallible requests
Closes #540
1 parent 4020f9a commit 7c17a05

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

docs/javascript/components_rpc_api.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ The module should roughly map to the route parameters for simplicity, for exampl
1313
The `Result` module provides a consistent interface to interact with the API.
1414
A comprehensive implementation can be found in `WoltLabSuite/Core/Api/Comments/RenderComment.ts`:
1515

16+
!!! info "WoltLab Suite 6.2 added a helper method for infallible requests that greatly reduces the boiler-plate code required for RPC endpoints that do not return errors in general. It is strongly recommended to use this new function instead unless you explicitly need to handle errors yourself. See the section on infallible requests to learn more."
17+
1618
```ts
1719
import { prepareRequest } from "WoltLabSuite/Core/Ajax/Backend";
1820
import { ApiResult, apiResultFromError, apiResultFromValue } from "WoltLabSuite/Core/Api/Result";
@@ -68,3 +70,24 @@ Any network errors or other kind of client errors will fail hard.
6870

6971
The returned value from the server will be attempted to be parsed into an `WoltLabSuite/Core/Api/Error` that represents the well-defined error response from the PHP RPC API.
7072
Validation errors can easily be detected through the `.getValidationError()` method of `ApiError` which returns `undefined` for all other error classes.
73+
74+
## Infallible RPC Requests
75+
76+
An RPC request is considered infallible if there is no reasonable situation where the request should ever fail.
77+
This is true for most RPC endpoints that do not explicitly return errors and instead should only fail if something unexpected goes wrong.
78+
79+
Using `ApiResult` requires the developer to explicitly handle unexpected errors either explicitly or implicitly through `.unwrap()` on the result.
80+
There have been cases where developers only checked for `if (result.ok) { /* … */ }` but completely neglected the error that was returned by the server.
81+
82+
It is strongly recommended to use this simplified call instead whenever you are not expecting any errors to be returned from the API call.
83+
84+
```ts
85+
import { prepareRequest } from "WoltLabSuite/Core/Ajax/Backend";
86+
import { fromInfallibleApiRequest } from "../Result";
87+
88+
export async function deleteSession(sessionId: string): Promise<[]> {
89+
return fromInfallibleApiRequest(() => {
90+
return prepareRequest(`${window.WSC_RPC_API_URL}core/sessions/${sessionId}`).delete().fetchAsJson();
91+
});
92+
}
93+
```

0 commit comments

Comments
 (0)