React restClient admin-on-rest

问题描述 投票:0回答:3

admin-on-rest 允许通过编写自定义休息客户端来使用任何 JSON 响应。文档中的示例用于从 json-server project 使用 JSON,这很简单。

我想知道在 admin-on-rest 中使用 这个 api 并稍微更改 restClient 有多容易。

json rest reactjs admin-on-rest
3个回答
0
投票

好吧 - 让我们研究一下 admin on rest 的来源(文件 admin-on-rest/src/util/fetch.js),我们对 fetchJson 方法感兴趣。

该方法返回 fetch Promise,其中尝试解析该代码中的 json:

try {
  json = JSON.parse(body);
} catch (e) {
  // not json, no big deal
}

然后返回:

return { status, headers, body, json };

但是我们在结果中有主体并且可以重用它,或者我们可以在 json 中使用解析后的对象

对于您的示例,我们可能会这样做(遗漏了一些代码):

const httpClient = (url, options = {}) => {
    if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' });
    }
    options.withCredentials = true;
        return fetchUtils.fetchJson(url, options).then(({status, headers, body, json}) => {
        json = json['results'] ? json['results'] : json;
        return {status, headers, body, json};
    });
}

因此,我们只是通过该行中模式中“结果”的集合覆盖了 json 对象:

json = json['results'] ? json['results'] : json;

现在您可以在管理中使用该客户端

<Admin restClient={restClient}>
...
</Admin>

警告!!!这将影响管理员的所有请求。但您可以添加额外的参数。如果您不想使用

json = json['results'] ? json['results'] : json;
,您可以添加额外的参数或签入方法fetch


0
投票

我建议你看看https://github.com/dev-family/admiral 它刚刚推出,但已经被证明是一件好事。我认为它应该可以帮助您解决问题。


-1
投票

如果我没记错的话,您想要重写以下网址(例如): https://marmelab.com/admin-on-rest-demo/#/customers/684 到: https://marmelab.com/admin-on-rest-demo/?customers=684

您可以重写restClient.js中的GET_ONE: 案例 GET_ONE: 网址=

${apiUrl}/${resource}/${params.id}
; 到: 案例 GET_ONE: 网址=
${apiUrl}/?${resource}=${params.id}
;

这将通过参数而不是 url 部分检索记录。

© www.soinside.com 2019 - 2024. All rights reserved.