Skip to content

Commit

Permalink
Add details mapping helpers to HTTPError
Browse files Browse the repository at this point in the history
  • Loading branch information
George-Payne committed Jan 15, 2025
1 parent e63b24d commit 818bf6a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 1 deletion.
47 changes: 47 additions & 0 deletions .changeset/rare-hats-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
'@kurrent-ui/utils': minor
---

`HTTPError` has two new helper methods for modifying it's problem details

### `HTTPError.mapProblemDetails`

Allows you to create a new HTTPError that will call the passed mapping function on it's details.

Example usage:

```ts
try {
await callAPI();
} catch (e) {
if (HTTPError.isHTTPError(error)) {
throw error.mapProblemDetails((details) => ({
...details,
title: "Its's okay..",
}));
}

throw error;
}
```

### `HTTPError.mapFieldKeys`

Allows you to create a new HTTPError that will call the passed mapping function on it's detail's field keys.

Example usage:

```ts
try {
await callAPI();
} catch (e) {
if (HTTPError.isHTTPError(error)) {
throw throw error.mapFieldKeys((key) =>
key.replace(/^chicken/, 'turkey'),
);
}

throw error;
}

```
29 changes: 28 additions & 1 deletion packages/utils/src/HTTPError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const defaultExtractDetails: ExtractDetails = async (response) => {

const ERROR_KEY = Symbol.for('HTTPError');

/** A standardised HTTP request error. Works together with [Working Data](/fields/utils/createWorkingData) to assign HTTPProblemDetails fields to errors on form fields. */
/** A standardised HTTP request error. Works together with @kurrent-ui/forms to assign HTTPProblemDetails fields to errors on form fields. */
export class HTTPError extends Error {
static isHTTPError(error: unknown): error is HTTPError {
return error instanceof Error && ERROR_KEY in error;
Expand Down Expand Up @@ -68,4 +68,31 @@ export class HTTPError extends Error {
}
return this.detailsPromise;
};

/** Returns a new HTTPError that calls the passed function on it's details when they are read. */
public mapProblemDetails = (
callbackfn: (details: HTTPProblemDetails) => HTTPProblemDetails,
): HTTPError =>
new HTTPError(this.response, async () => {
const details = await this.details();
return callbackfn(details);
});

/** Returns a new HTTPError that calls the passed function on it's detail's fields when they are read. */
public mapFieldKeys = (
callbackfn: (key: string, value: string) => string,
): HTTPError =>
this.mapProblemDetails((details) => {
if (details.fields == null) return details;
const { fields, ...rest } = details;
return {
...rest,
fields: Object.fromEntries(
Object.entries(fields).map(([key, value]) => [
callbackfn(key, value),
value,
]),
),
};
});
}

0 comments on commit 818bf6a

Please sign in to comment.