【发布时间】:2021-09-11 09:31:15
【问题描述】:
我正在拨打Shopify admin api。
当我使用 REST API 时,我的响应中会出现漂亮的 JSON 对象。
[{
{
"id": 7036594978985,
"title": "7 Shakra Bracelet",
"body_html": "<p>7 chakra bracelet, in blue or black.</p>",
"vendor": "Company 123",
"product_type": "Bracelet",
"created_at": "2021-06-17T17:45:05-04:00",
"handle": "chain-bracelet",
"updated_at": "2021-06-23T20:08:21-04:00",
"published_at": "2021-06-17T17:45:04-04:00",
"template_suffix": null,
"published_scope": "web",
"tags": "Beads, Bracelet",
"admin_graphql_api_id": "gid://shopify/Product/7036594978985",
"variants": [
{
"id": 40671266963625,
"product_id": 7036594978985,
"title": "Blue",
"price": "42.99",
"sku": null,
"position": 1,
"inventory_policy": "deny",
"compare_at_price": "44.99",
"fulfillment_service": "manual",
"inventory_management": null,
"option1": "Blue",
}
},
{
id: 7036594978986
...
]
但是,如果我使用 GraphQL,我最终会得到一堆边和节点,这些边和节点不能很好地与我的前端 JS 配合使用。
{
"products": {
"edges": [
{
"node": {
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
"handle": "skirt",
"id": "gid://shopify/Product/4773734482089",
"images": {
"edges": [
{
"node": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
}
},
{
"node": {
"id": "gid://shopify/ProductImage/26072838406313",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb7.jpg?v=1612636091"
}
},
{
"node": {
"id": "gid://shopify/ProductImage/26072838373545",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb6.jpg?v=1612636091"
}
}
]
},
我想通过用友好的最小 JSON 结构替换所有边和节点来稍微扁平化数组。
从这里:
{
"products": {
"edges": [
{
"node": {
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
到这里:
{
"products": [
{
"description": "Sleek and black",
"featuredImage": {
"id": "gid://shopify/ProductImage/15464783282345",
"originalSrc": "https://cdn.shopify.com/s/files/1/0268/1005/6873/products/bb20.jpg?v=1602116082"
},
我希望能够调用递归 PHP 函数来替换嵌套在数组中的所有节点和边。
我试过这个,但我认为它会导致迭代问题。
public function parse_and_remove (&$arr) {
foreach ($arr as $key => $val) {
if (($key == 'edges' || $key == 'node') && (is_array($val) || is_object($val))) {
$arr = $val;
$val = $this->parse_and_remove($val);
} else if (is_array($val) || is_object($val)) {
$val = $this->parse_and_remove($val);
} else {
}
}
return $arr;
}
第二部分
每个人都对 GraphQL 中的这种响应感到满意吗?在经常使用 API 响应的前端工作是一件痛苦的事情。不要给我边数组和节点,最后是对象。我只想要那个对象数组:)
【问题讨论】:
-
什么前端问题?只是
images.edges.map( {node} => <SomeImage key={node.id} url={node.originalSrc} />- 不需要“扁平化”:p - 你没有使用分页[关于关系],我猜 -
有一百万种不同的组件和插件不需要节点和边。
-
对吗?一个具体的?再次,什么 FE [lib] 可能有问题?扁平化可以在 js
.maponeliner 中完成,不值得 BE 努力
标签: php json recursion graphql shopify