From 66dca9c2fa5b4841c350f62e575a0f9ad7249a61 Mon Sep 17 00:00:00 2001 From: Antoine Bluchet Date: Sat, 9 Nov 2024 11:15:33 +0100 Subject: [PATCH] fix: use patch by default (#589) --- src/hydra/dataProvider.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/hydra/dataProvider.ts b/src/hydra/dataProvider.ts index a7efd355..385cc405 100644 --- a/src/hydra/dataProvider.ts +++ b/src/hydra/dataProvider.ts @@ -182,7 +182,7 @@ function normalizeHydraKey(json: JsonLdObj, key: string): JsonLdObj { * GET_LIST => GET http://my.api.url/posts * GET_MANY => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789 * GET_ONE => GET http://my.api.url/posts/123 - * UPDATE => PUT http://my.api.url/posts/123 + * UPDATE => PATCH http://my.api.url/posts/123 */ function dataProvider( factoryParams: HydraDataProviderFactoryParams, @@ -253,13 +253,10 @@ function dataProvider( }; const transformReactAdminDataToRequestBody = ( - resource: string, + apiResource: undefined | Resource, data: Record | XMLHttpRequestBodyInit, extraInformation: { hasFileField?: boolean }, ): Promise => { - const apiResource = apiSchema.resources.find( - ({ name }) => resource === name, - ); if (undefined === apiResource) { return Promise.resolve(data as XMLHttpRequestBodyInit); } @@ -366,12 +363,23 @@ function dataProvider( if (typeof params.meta === 'object') { extraInformation = params.meta; } - const updateHttpMethod = extraInformation.hasFileField ? 'POST' : 'PUT'; + + const apiResource = (apiSchema?.resources ?? []).find( + ({ name }) => resource === name, + ); + + let updateHttpMethod = 'POST'; + + if (!extraInformation.hasFileField) { + updateHttpMethod = + apiResource?.operations?.find((operation) => operation.type === 'edit') + ?.method ?? 'PUT'; + } switch (type) { case CREATE: return transformReactAdminDataToRequestBody( - resource, + apiResource, (params as CreateParams).data, extraInformation, ).then((body) => ({ @@ -481,13 +489,17 @@ function dataProvider( case UPDATE: return transformReactAdminDataToRequestBody( - resource, + apiResource, (params as UpdateParams).data, extraInformation, ).then((body) => ({ options: { body, method: updateHttpMethod, + headers: + updateHttpMethod === 'PATCH' + ? { 'content-type': 'application/merge-patch+json' } + : {}, }, url, }));