Leveraging the power of Fractal Transformer in conjunction with ember-data

While using the PHP league's Fractal as the transformer for my API, I have encountered an issue where the item transformer is wrapping everything in an array similar to a collection. This goes against the standards set by the JSON API.

For instance, when retrieving a user with ID of one, the response looks like this:

{  
"users":[  
   {  
      "id":1,
      "firstName":"Jacob",
      "surname":"Windsor",
   }
  ]
}

It should actually look like this:

{  
"users":
   {  
      "id":1,
      "firstName":"Jacob",
      "surname":"Windsor",
   }
}

This inconsistency is causing issues with naming conventions in Ember.js.

In my Laravel userController, the code snippet looks something like this:

public function show($id)
{
    $user = User::find($id);
    return $this->respondItem($user);
}

This issue stems from the apiController, which all controllers extend:

public function respond($response, $status = 200){
    return Response::make($response, $status);
}


public function respondTransform($resource){
    $fractal = new Fractal\Manager();
    $fractal->setSerializer(new JsonApiSerializer());
    return $this->respond($fractal->createData($resource)->toJson());
}

public function respondItem($data, $transformer = null, $namespace = null){
    ! isset($transformer) ? $transformer = $this->transformer : $transformer = $transformer;
    ! isset($namespace) ? $namespace = $this->namespace : $namespace = $namespace;
    $resource = new Item($data, $transformer, $namespace);
    return $this->respondTransform($resource);
}

It seems like there might be an error in my implementation. The documentation for Fractal doesn't provide examples specifically for items, only collections. As a result, I am unsure about the mistake I may have made.

Answer №1

It appears that Fractal does not exactly follow ember-data's conventions, presenting a frustrating issue that can be easily resolved by utilizing custom serializers.

To tackle this problem, I have implemented a psr-4 autoloaded file named CustomJsonSerializer within my ApiController class. By following the instructions provided on php league's website (linked above), implementing these two methods is quite straightforward.

public function collection($resourceKey, array $data)
{
    return array($resourceKey ?: 'data' => $data);
}

/**
 * Serialize an item resource
 *
 * @param string $resourceKey
 * @param array $data
 *
 * @return array
 */
public function item($resourceKey, array $data)
{
    return [$resourceKey => $data];
}

The collection method behaves as expected, with no changes necessary. However, the item method responds without the additional array, providing a simple solution. While I have yet to address pagination, it should be a relatively straightforward task.

I trust that this information proves beneficial to those looking to integrate ember-data with Fractal. I personally endorse its usage, as Fractal has significantly eased my workflow. Although creating transformers manually is possible, using Fractal simplifies the process and allows for easier modifications in the future.

Edit:

Ensure that you retain the use of $resourceKey in both methods. This variable must be utilized and defined when invoking the transformer, as Ember-data necessitates a resource key.

Answer №2

In the scenario where your userController is an extension of the ApiController, a simple approach would be:

public function display($identifier)
{
    $individual = User::findUserByID($identifier);

    return $this->setStatus(200)->demonstrateItem($individual, new CustomUserTransformer);
}

It is essential to construct the CustomUserTransformer category. If you require assistance with this process, kindly inform me through the feedback section.

Answer №3

I discovered that a simple modification to the JsonApiSerializer worked perfectly for my needs in Ember:

(I removed the count($data) check)

<?php
namespace Acme\Serializer;

use RuntimeException;

use League\Fractal\Serializer\JsonApiSerializer;

class EmberSerializer extends JsonApiSerializer
{


    /**
     * Custom serialization of top level data.
     *
     * @param string $resourceKey
     * @param array $data
     *
     * @return array
     */
    public function serializeData($resourceKey, array $data)
    {
        if (! $resourceKey) {
            throw new RuntimeException('The $resourceKey parameter must be provided when using '.__CLASS__);
        }

        return array($resourceKey => $data);
    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving information via RESTful API using jQuery

Seeking assistance with integrating a JSON feed into an HTML document using jQuery. For instance, I am trying to extract the "base_title" and display it in an h2 tag. Any insights on how to achieve this would be greatly appreciated. Your help will be high ...

Manage how data is presented in a JSON format using Go's structures

Currently, I am working on a nested structure in golang and trying to manage which substructures should be displayed in JSON. For example, if I only want to show the treeid and name fields from Citrus, I attempted the following notation, but it still prin ...

NodeJs google analytics reporting API returning null response object

Just getting started with a question. In my project, I am utilizing NodeJS to interact with the Google Analytics Reporting API. I have successfully obtained the necessary OAuth 2 token and even receive a 200 response when querying the API. However, instea ...

Axios consistently produces results in the form of strings but always seem to omit the final

I'm encountering an issue with my axios post method. public function viewAuthCheck(Request$request){ return [ 'test' => 'hello!' ]; } Here is my axios function: axios.post('/timetracking/settings/auth/check ...

Converting std::list to JSON using Boost Property Tree

After struggling with this problem for the past few days, I am still unable to figure it out. I have a std::list container that I need to serialize into a JSON string in order to send it over the network. NOTE: This is how I compile my code: g++ -std=c++ ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

Populate ComboBox with JSON data in an ExtJS application

I am a beginner in the world of jsp and ExtJS. I have a jsp file where I am making an AJAX request to a servlet. The servlet responds with a JSON string. However, despite receiving the data, I am unable to populate a ComboBox with it. Let's take a lo ...

What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons. const url = 'http://newsapi.org/v2/everything?' + 'q=platformer&' + 'apiKey=3ce15c4d1fd3485cbcf17879bab498db'; ...

What limitations prevent the Jersey/JAX-RS client from effectively processing generics?

I am currently working with a Jersery/JAX-RS client that interacts with a RESTful API (JSON), specifically designed to retrieve a list of my POJOs: // Hits: GET localhost:8080/myapp/fizz/widget/{widget_id} @Override public List<Widget> getWidgetsByU ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Using Grep, transform an existing JSON object into a new JSON object by applying a grep or delete operation

Consider the JSON object below: var data = { "ok" : true, "messages" : [ { "type" : "message", "subtype" : "bot_remove" }, { "type":"message", "subtype":"file_share", ...

Python program that runs a loop through a file, sends API requests using the `requests` library, and saves the results

Currently working on a program to loop through movie titles in a text file and make API calls to store the responses. The text file contains a single title on each line, for example: Titanic Avatar A Star Is Born The API being used is from a website ca ...

unable to decipher a JSON file obtained from Instagram

I have been working on a project that involves parsing a JSON file obtained from the Instagram API. However, I am facing an issue where I can parse the data but I cannot read it properly in my code: <!DOCTYPE html> <html> <head> <meta ...

Guide to sending an Array of objects in the request body using RestAssured in Java

Here is the Request I am working with: [ { "userId": "value1" },{ "userId": "value2" } ] I attempted to create a POJO class and construct the request, as well as using an ArrayList, but there ...

What is the best way to craft an if/else statement for a situation when a twig variable is undefined?

When utilizing twig to declare a variable called user: <script type="text/javascript> {% if user is defined %} var user = { example: {{ userjson | raw }} }; {% endif %} </script> If a user is not logged in, an error message a ...

Saving several inputs with incremented values

I'm facing an issue with saving data from multiple input fields in a for loop: <input type="number" name="device_id_1"> <input type="number" name="device_id_2"> ... <input type="number" name="name_1"> <input type="number" name="n ...

Retrieving server-side data in Next.js

As I dive into the world of Next.js coming from React, I've been able to make things work for the most part. However, when I tried creating a server component to test server-side fetching, I encountered some strange issues. Usually, when I start the ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

Exploring the depths of nested JSON with Angular2

I'm a beginner in Angular 2 using Typescript. I am trying to figure out how to access the 'D' and 'G' elements in my JSON data using NgFor. Is there a specific way or method that I can use to achieve this? [ { "A":"B", "C" ...

The Laravel return view function seems to be malfunctioning as it is displaying an error page instead

I am facing an issue where I am trying to display an existing view but instead of the show page, I keep getting a "404 not found" error. As a beginner in Laravel, I am still trying to grasp its concepts. Any insights into why I am encountering the error 40 ...