Skip to content

Commit

Permalink
Type guard the middleware action
Browse files Browse the repository at this point in the history
To tighten the type safety for ´extractServiceBaseUrls´ we validate the incoming action against a type guard
  • Loading branch information
JacobArrow committed Nov 22, 2024
1 parent a9c00d3 commit 65dd104
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/core/utils/reduxMiddleware/extractServiceBaseUrls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ export type ServiceBaseUrls =
| Record<Api, ApiBaseUrlKey>
| Record<string, never>;

type Action = {
type: string;
payload: {
entries: ServiceBaseUrls;
};
};

type ServiceBaseUrlKey = keyof ServiceBaseUrls;

export const serviceUrlKeys = {
Expand All @@ -43,15 +50,23 @@ const filterUrls = (
return { ...obj, ...{ [key]: urls[key as Api] } };
}, {});

// Type guard Action
const isAction = (action: any): action is Action => {
return (
action &&
action.type === "url/addUrlEntries" &&
action.payload &&
typeof action.payload.entries === "object"
);
};

// Redux middleware that extracts the service base urls from the action
// and stores them in the serviceBaseUrls "store".
const extractServiceBaseUrls: Middleware<
Record<string, never>,
EnhancedStore
// we need to use any here because we don't know the action type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
> = () => (next) => (action: any) => {
if (String(action.type) === "url/addUrlEntries") {
> = () => (next) => (action) => {
if (isAction(action)) {
const {
payload: { entries }
} = action;
Expand Down

0 comments on commit 65dd104

Please sign in to comment.