FriendsOfCake / crud-json-api

Build advanced JSON API Servers with almost no code.
https://crud-json-api.readthedocs.io/
MIT License
55 stars 30 forks source link

Fieldsets: Specifying underscore_field does not work #142

Closed rchavik closed 3 years ago

rchavik commented 3 years ago

Without specifying fieldset, the response return something like:

{
   data: [
     {
        attributes: [
           title: '....',
           commentCount: 0,
        ],
     },
     { ... }
   ]
}

However, specifying fields[nodes]=commentCount does not work. Neither using fields[nodes]=comment_count.

Following patch solves this. But this assumes that the physical fields are always using underscore format. Any suggestion?

diff --git a/src/Listener/JsonApiListener.php b/src/Listener/JsonApiListener.php
index ff1c547e..c7e2a9a2 100644
--- a/src/Listener/JsonApiListener.php
+++ b/src/Listener/JsonApiListener.php
@@ -484,7 +484,7 @@ class JsonApiListener extends ApiListener
         // format $fieldSets to array acceptable by listener config()
         $fieldSets = array_map(
             static function ($val) {
-                return explode(',', $val);
+                return explode(',', Inflector::underscore($val));
             },
             (array)$fieldSets
         );
diff --git a/src/View/JsonApiView.php b/src/View/JsonApiView.php
index 8eb23577..fe014b7f 100644
--- a/src/View/JsonApiView.php
+++ b/src/View/JsonApiView.php
@@ -236,6 +236,12 @@ class JsonApiView extends View
         $include = $this->getConfig('include');
         $fieldSets = $this->getConfig('fieldSets');

+        $fieldSets = array_map(function($fields) {
+            return array_map(function($field) {
+                return \Cake\Utility\Inflector::variable($field);
+            }, $fields);
+         }, $fieldSets);
+
         $encoder
             ->withIncludedPaths($include)
             ->withFieldSets($fieldSets);