Eloquent: API Resources vs Fractal - laravel

Quick question, what is the difference between Eloquent: API Resources and Fractal?
To me, it looks like the same thing?

Both are used to transform API json responses to standardise the response structure.
However, API resources is inbuilt in Laravel and it's very easy to use. Fractal was the preferred way to go when API resources were not in-build in Laravel. Fractal has some methods which make it little extensive as compared to API resources.
But if you consider the core functionality, both are same with different syntactical sugar.
Most of the things which were in fractal, you can do natively in Laravel now. Plus API resources eliminate the need of any extra installation and setup. The nomenclature is very easy in API resources to start with

both of them are created for one job but their solutions are different in many ways.
Relationships:
in fractal you can easily add related models to the response. also, you can control when the related models should be presented in the response . (default include vs Available include)
for example your client can use ?include=rate to get the rate model from an article when needed! consider that, the fractal will eager load your relationships when you forgot to load it.
in API Resources you have no control over relationships and you should decide to have relationship or not in the first place. otherwise, if you forgot to eager load data for it, it will cost you too many queries to load related model (1+n problem).
Serializer
in basic usage of api resource you have no control on how data will map to final response.
for example if you want jsonnapi specification for your responses, you should manage all of the works by yourself. but in fractal you have it in the first place.
as a conclusion
i recommend you to use fractal in this case. (or use dingo package for api but consider complexity of dingo !!)

Related

Entities or Models in NestJs code first GraphQl

I am new to NestJs and GraphQl, I am learning going over some tutorials. It appears to be an inconstancy in the usage of the terminology model or entity. The nestjs schematics resource generator for graphql code first produces entities, yet the example shown on their website use models.
produces entities:
nx generate #nestjs/schematics:resource generated --language=ts --type=graphql-code-first
uses models no mention of entities in code first approach
https://docs.nestjs.com/graphql/resolvers
which one terminology is most appropriate?
Thank You,
Michael
Both are generally correct. It comes down to naming preferences.
I view entities as database entities, or database table maps. They map from your database data to a class representation that your code will understand. Models can also be used for this, which I believe is the term that sequilize and mongoose prefer to use.
Models, as described in the docs you linked, are generally your DTOs, your schema objects that you expect the API to accept and respond with.
You'll notice that the generator also generates two #InputType() files as well, which will be more closely tied to your incoming DTO while the entity.ts will be closer to your response DTO.
So, both are correct, and it comes down to naming preferencec.

What is best solution use VUEX (nuxt.js) for CRUD operators with API?

What is the best solution for deleting, editing, retrieving, and creating a record using VUEX and AXIOS?
I think this is what is the best and most logical architecture?
If it's possible give me examples
Thanks
One way to reason about your Vuex modules is to think of them as representations of your various resources, often represented by models on your backend. For example, you could have a user module, an article module or a movie module, depending on your application.
Then, you will probably need an action for each CRUD operation. For R, read, you might want to use two: one for fetching a single entry and another for fetching a list of items.
Let's say you're working with movies. You'd most likely need five actions that could be named as follows: fetchMovies, fetchMovie, createMovie, updateMovie, deleteMovie.
Each of these would have to be async actions where you would await a response from your axios calls.
Once you have the responses, you need to set up relevant mutations for each of these actions where you can modify the state accordingly.
This is a very rudimentary description of what your approach might be and Vuex and Nuxt are both rather flexible.
I recommend you read through the Vuex documentation and the Vuex-related sections of the Nuxt documentation, both are very well written and cover much more than what I could here.

Is there a policy definition language for GraphQL APIs?

Is there a way for us to define the policies of a GraphQL API, which is both machine-readable and human-readable, which contains a set of rules (in other words, a specification) to describe the format of the API? I'm not talking about the schema, but of a spec where we can add security-related details (for example, complexity value to be assigned per field and depth limitation values) or any other related details. Any thoughts or ideas? Or can we send all of this within the SDL itself?
For example, for REST APIs, we use Swagger to define information on how to define paths, parameters, responses, models, security and more. Is there a need for a similar approach for GraphQL APIs? Your response is highly appreciated
We are working in an approach to add policies to your GraphQL API and allow you to better manage it, especially as you expose the interface externally.
Part of the challenge is that as opposed to a REST call that can easily be differentiated from others, all GraphQL requests look the same, unless a deeper analysis is performed on the incoming query.
This blog post describes how we perform this analysis: https://www.ibm.com/blogs/research/2019/02/graphql-api-management/
if this is of interest let's connect!
As per my understanding you need a tool to make documentation for the APIs you have build for parameters and so on.
If that's what you are searching, there is like swagger for GraphQL - Swagger-to-GraphQL
Hope that helps.!!

Standardizing data structures between different platforms

Imagine, for example, you have front-end and back-end applications. They are both written in different technologies, lets say backend is in python using django and front end in typescript using angular.
Now there will be some data that will need to be shared between those two. Enums, serialized dictionaries of class instances or names of some fields.
Very quickly a problem arises of data structure duplication and possibility of desynchronisation. (E.g. you have to have to exact enums on both platforms)
I was wondering are there any "best practices" out there?
Like XML based standardizing data or something?
Could you point me to some books / articles?
Could you share your knowledge of how you do this?
Thank you.
I know two ways to solve this obstacle:
Write your own clients for consumers.
Use model contracts like RAML and generate models from declarations.
And you don't have to have the same exact enum or any other class on both platforms. There should be a layer that consumes and returns any data to the outside world(external client). This layer has its own models. Everything that lies below should have their own. You can have many small objects stored in database, but return to the client huge aggregates and that would be different models. Read about data models in standard N-tier application.

Streamlining the implementation of a Repository Pattern and SOA

I'm working with Laravel 5 but I think this question can be applied beyond the scope of a single framework or language. The last few days I've been all about writting interfaces and implementations for repositories, and then binding services to the IoC and all that stuff. It feels extremely slow.
If I need a new method in my service, say, Store::getReviews() I must create the relationship in my entity model class (data source, in this case Eloquent) then I must declare the method in the repo interface to make it required for any other implementation, then I must write the actual method in the repo implementation, then I have to create another method on the service that calls on the repo to extract all reviews for the store... (intentional run-on sentence) It feels like too much.
Creating a new model now isn't as simple as extending a base model class anymore. There are so many files I have to write and keep track of. Sometimes I'll get confused as of to where exactly I should put something, or find halfway throught setting up a method that I'm in the wrong class. I also lost Eloquent's query building in the service. Everytime I need something that Eloquent has, I have to implement it in the repo and the service.
The idea behind this architecture is awesome but the actual implementation I am finding extremely tedious. Is there a better, faster way to do things? I feel I'm beeing too messy, even though I put common methods and stuff in abstract classes. There's just too much to write.
I've wrestled with all this stuff as I moved to Laravel 5. That's when I decided to change my approach (it was tough decision). During this process I've come to the following conclusions:
I've decided to drop Eloquent (and the Active Record pattern). I don't even use the query builder. I do use the DB fascade still, as it's handy for things like parameterized query binding, transactions, logging, etc. Developers should know SQL, and if they are required to know it, then why force another layer of abstraction on them (a layer that cannot replace SQL fully or efficiently). And remember, the bridge from the OOP world to the Relational Database world is never going to be pretty. Bear with me, keeping reading...
Because of #1, I switched to Lumen where Eloquent is turned off by default. It's fast, lean, and still does everything I needed and loved in Laravel.
Each query fits in one of two categories (I suppose this is a form of CQRS):
3.1. Repositories (commands): These deal with changing state (writes) and situations where you need to hydrate an object and apply some rules before changing state (sometimes you have to do some reads to make a write) (also sometimes you do bulk writes and hydration may not be efficient, so just create repository methods that do this too). So I have a folder called "Domain" (for Domain Driven Design) and inside are more folders each representing how I think of my business domain. With each entity I have a paired repository. An entity here is a class that is like what others may call a "model", it holds properties and has methods that help me keep the properties valid or do work on them that will be eventually persisted in the repository. The repository is a class with a bunch of methods that represent all the types of querying I need to do that relates to that entity (ie. $repo->save()). The methods may accept a few parameters (to allow for a bit of dynamic query action inside, but not too much) and inside you'll find the raw queries and some code to hydrate the entities. You'll find that repositories typically accept and/or return entities.
3.2. Queries (a.k.a. screens?): I have a folder called "Queries" where I have different classes of methods that inside have raw queries to perform display work. The classes kind of just help for grouping together things but aren't the same as Repositories (ie. they don't do hydrating, writes, return entities, etc.). The goal is to use these for reads and most display purposes.
Don't interface so unnecessarily. Interfaces are good for polymorphic situations where you need them. Situations where you know you will be switching between multiple implementations. They are unneeded extra work when you are working 1:1. Plus, it's easy to take a class and turn it into an interface later. You never want to over optimize prematurely.
Because of #4, you don't need lots of service providers. I think it would be overkill to have a service provider for all my repositories.
If the almost mythological time comes when you want to switch out database engines, then all you have to do is go to two places. The two places mentioned in #3 above. You replace the raw queries inside. This is good, since you have a list of all the persistence methods your app needs. You can tailor each raw query inside those methods to work with the new data-store in the unique way that data-store calls for. The method stays the same but the internal querying gets changed. It is important to remember that the work needed to change out a database will obviously grow as your app grows but the complexity in your app has to go somewhere. Each raw query represents complexity. But you've encapsulated these raw queries, so you've done the best to shield the rest of your app!
I'm successfully using this approach inspired by DDD concepts. Once you are utilizing the repository approach then there is little need to use Eloquent IMHO. And I find I'm not writing extra stuff (as you mention in your question), all while still keeping my app flexible for future changes. Here is another approach from a fellow Artisan (although I don't necessarily agree with using Doctrine ORM). Good Luck and Happy Coding!
Laravel's Eloquent is an Active Record, this technology demands a lot of processing. Domain entities are understood as plain objects, for that purpose try to utilizes Doctrime ORM. I built a facilitator for use Lumen and doctrine ORM follow the link.
https://github.com/davists/Lumen-Doctrine-DDD-Generator
*for acurated perfomance analisys there is cachegrind.
http://kcachegrind.sourceforge.net/html/Home.html

Resources