Skip to content
This repository has been archived by the owner on Nov 11, 2023. It is now read-only.

Commit

Permalink
Implement resolve for Mutate
Browse files Browse the repository at this point in the history
  • Loading branch information
fabien0102 committed Mar 31, 2021
1 parent 81e4a51 commit 46b0584
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/Mutate.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from "react";
import RestfulReactProvider, { InjectedProps, RestfulReactConsumer, RestfulReactProviderProps } from "./Context";
import { GetState } from "./Get";
import { GetState, ResolveFunction } from "./Get";
import { composePath, composeUrl } from "./util/composeUrl";
import { processResponse } from "./util/processResponse";
import { constructUrl } from "./util/constructUrl";
Expand Down Expand Up @@ -108,6 +108,11 @@ export interface MutateProps<TData, TError, TQueryParams, TRequestBody, TPathPar
* to an existing path
*/
pathInlineBodyEncode?: typeof encodeURIComponent;
/**
* A function to resolve data return from the backend, most typically
* used when the backend response needs to be adapted in some way.
*/
resolve?: ResolveFunction<TData>;
}

/**
Expand Down Expand Up @@ -166,6 +171,7 @@ class ContextlessMutate<TData, TError, TQueryParams, TRequestBody, TPathParams>
onRequest,
onResponse,
pathInlineBodyEncode,
resolve,
} = this.props;
this.setState(() => ({ error: null, loading: true }));

Expand Down Expand Up @@ -224,7 +230,26 @@ class ContextlessMutate<TData, TError, TQueryParams, TRequestBody, TPathParams>
throw error;
}

const { data, responseError } = await processResponse(response);
const { data: rawData, responseError } = await processResponse(response);

let data: TData | any; // `any` -> data in error case
try {
data = resolve ? resolve(rawData) : rawData;
} catch (e) {
if (this.signal.aborted) {
return;
}
const error = {
data: e.message,
message: `Failed to resolve: ${e.message}`,
};

this.setState({
error,
loading: false,
});
throw e;
}

// avoid state updates when component has been unmounted
if (this.signal.aborted) {
Expand Down

0 comments on commit 46b0584

Please sign in to comment.