Best practice for bidirectional external API mapping? #462
Unanswered
tobias-grasse
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
My application needs to synchronize models (= read & write) with a third-party JSON REST API. It looks like
laravel-data
is a great fit for that purpose, but I wonder what the best practices for this use case are.To explain by example: I need to synchronize my
Client
Eloquent model with aClientContact
resource on the third-party API.Some properties need just a name mapping:
firstName
(API) <->given_name
(Eloquent). Others are more complex:id
(API) <->external_id
attribute on theprofile
relationship of myClient
model.Example API response:
ERD of my Eloquent models:
![image](https://private-user-images.githubusercontent.com/834914/242530961-440c594f-0ef5-4729-a3ad-9f8c14ece2bf.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3Mzk1ODM5NzAsIm5iZiI6MTczOTU4MzY3MCwicGF0aCI6Ii84MzQ5MTQvMjQyNTMwOTYxLTQ0MGM1OTRmLTBlZjUtNDcyOS1hM2FkLTlmOGMxNGVjZTJiZi5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMjE1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDIxNVQwMTQxMTBaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT03ZGQxMDM2OTQxZTMzYWIyNGQ2NzY3NDc3NGZiNzRhM2IwYTVkNzc4NmM3MGVkNDU3ZjFiMGM2NzUxNWY3N2QyJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.KtNAohgsFMPRf9kdA-iFJyN3ZH7irtMDwXKqMcVdMrY)
My
ClientData
object – properties currently aligned with the Eloquent model:My ideal solution would be something along these lines:
I experimented with the
Map{Input,Output}Name
attributes and thefrom<Type>
magic methods, but sooner or later I find myself repeating the mapping in both directions. Maybe I'm holding it wrong™?If I understand the package code correctly, the
JsonNormalizer
will decode the API response string to an associative array, which is passed to theClientContactData
constructor. Do I need to override bothfromArray
andfromModel
to map both ways?Beta Was this translation helpful? Give feedback.
All reactions