goodie
6 months ago
766
4
General

Data transformation.

Posted 6 months ago by goodie

Hello!

Currently I'm building some application and there's support section. There are two types of users: user and agent (admin). The problem is I can't transform API data properly. The format I'd like to use:

{
   "id": 1,
   "title": "Title of question",
   "user_id": 1, 
   "messages": [
     {
       "id":  2,
        "message": "Message text",
        "agent": { // All agents should have "agent" key in their message
              id: 5,
              name: "Agent #5",
              photo: "https://example.com/avatar.png"
         }
     },
     {
       "id":  3,
        "message": "User message text",
        "user": { // All users should have "user" key in their message
              id: 6,
              name: "Jack Snow",
              photo: "https://example.com/user_avatar.png"
         }
     }
   ]
}

I should explain it a little bit more: user and agent objects are objects from my User model. This model has photo, name, admin (0/1) and id.

I tried to use transformers from this https://github.com/gothinkster/laravel-realworld-example-app/tree/master/app/RealWorld/Transformers app, but it doesn't looks correctly, because solution looks like this:

// QuestionTransformer
$data = $question->toArray();
        
 $messages = new MessageTransformer($question->messages);
 $data['messages'] = $messages->mappedData;

// MessageTransformer

$user = $message->user;
$isAdmin = $user->isAdmin(AccountAdminLevel::HELPER);

$userArray = [
    'name' => $isAdmin ? 'Agent #' . $user->id : $user->name,
];

$messageMerge = [];
$messageMerge[$isAdmin ? 'agent' : 'user'] = $userArray;

return array_merge($message->toArray(), $messageMerge);

It's not clear i think. Also this solution is not scalable: how can I, for example, instead of all messages use in this transformer just last message?

So my question is: how to properly transform data in format I've provided above? Is there are any useful libraries?

Thank you!

Please sign in or create an account to participate in this conversation.