Storing data in factories or services? - angularjs

https://github.com/johnpapa/angular-styleguide#style-y060
Shows a single responsibility factory making $http requests and handling some logic and errors, returning the promise. Typically from there, I would store the results in a service (as opposed to controller $scope so I can access it anywhere, including in directives). However:
Conversely, don't create a service whose only purpose in life is to
store and return bits of data.
https://docs.angularjs.org/misc/faq
Should I store the data on the factory itself? Or continue with factory -> http / service -> storage?
I'm not asking what the code difference is between the two, "one can be new'd etc", I'm asking for those that follow Angular best practices (skinny controllers, etc) what are the rules concerning the roles of a factory after it's fetched the data?

Should I store the data on the factory itself? Or continue with
factory -> http / service -> storage?
I see nothing wrong here. And don't forget, there are constant and value that fit nicely to 'store and return bits of data'. And caching solutions (i.e. $cacheFactory, angular-cache) that can help you to improve app design.
You can't blame Angular FAQ for advocating $rootScope, but keep in mind that it could be an obsolete opinion of some team member. Things have changed in Angular, and opinions have also changed in Angular community. You shouldn't trust a single developer on how exactly you should write your code (even if Papa is the surname), but it surely wasn't he who introduced the questionable concept of 'scope' into JS framework that was later anathematized even by its creator.

Related

Angular 1.x : Specific Scenario When To Use Controller / Service

Let's say, In a web app, a particular JSON is frequently used across multiple pages, for e.g:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
So getting a firstName() or lastName() for all employees should be considered as a part of the controller or the Service?
I could only think of using services as it is frequently used across app and controller be getting this data and it will be thinner too.
Is this right approach ?
You have following options:
Make a REST/HTTP call every time you need this data in a certain controller. Therefore, create a EmployeesService which calls the HTTP
endpoint to get the data.
Call the data once, and store it in a service. Afterwards, inject the service everywhere you need the data.
Fetch the data from the HTTP endpoint when your app starts, and store it in the local storage of the browser or inside the $rootScope,
so you can access it from everywhere.
In the end, it depends on:
How big is your app/how much data you have to share?
How often gets this data updated?
Which Views do need access to this data?
So yes, with a service, you are on a safe side. Afterwards, inject it into the controller and use it from there. How and how often the data gets into the service: Your decision.

External API calls from the frontend or backend?

Scenario:
I have a Node and Angular web app.
It needs to call an external api (a third party service) for data (more specifically this: https://api.represent.me/api/questions/).
Question:
Is it better to make this external call from the Angular frontend: GET http://thirdpartyservice.com/api/data or have the frontend calling a same domain Node endpoint: GET http://example.com/node-backend-api which then calls GET http://thirdpartyservice.com/api/data which then fetches and processes the data from the third party api before passing it back to angular?
Thoughts:
I guess two api calls is less desirable, but it is on the same domain
so would this not really be an issue?
GETing from the Node side would be more secure (especially if secret
keys were used), and also mask the fact that a third party service is
used.
CORS stuff might get in the way if calling from the frontend.
Is context key here, e.g. calling font apis from the
frontend is probably best, but fetching and needing to process data
is probably better from the backend.
What do others recommend (and do) and are there any other for or against points to add to the 'thoughts' too?
It depends on what your 3rd party API requires.
If you need some credentials to call the API it's probably better to handle the call in backend because of security concerns.
If the API delivers time sensitive data, like some auto-complete information as you type, it might be good to not do the extra roundtrip to the backend and call it from the frontend.
You might create a subdomain which points to the 3rd party server,
like 3rdparty-api.yourdomain.com, this removes a lot of cross-domain issues. But this needs cooperation of your 3rd party provider.
So, there is no clear yes or no answer but it depends on the situation and focus of your API.
Your solution looks fine, the only thing that may get in your way is if the 3rd party API you are using provides any sort of analytics. If you call it from Node you will overwrite the Agent and IP information that would be gathered if you called from UI. Other than that, I believe making the request directly from UI could reduce a little bit the load on the server, but I don't know if that matters to you.
I would say we should also take care about code duplication. In your case you are all JavaScript, but that is not true for many others. So let's say I consume api.github.com so I will not want to make some calls from frontend and some from the backend, then I think creating a controller which will handle all of this is a good choice.
Except for the cases like any analytics or tracking software, an extra round trip is ok.
As #Wolffc said, this can also prevent sending access_token to the browser which may be misused.

How can I have $http return mock data while a service endpoint is not ready?

In an Angular service (provider.service) that uses $http, is there a way to periodically turn on and off what certain calls using $http will return?
Here's my scenario: we are using $http to consume web services built by another development team. When those services are not yet ready (or break) we don't want development efforts to halt on our end. We simply need to temporarily turn off that specific call and have it return mocked data.
I've seen $httpBackend being used to mock out HTTP calls, but I'm not sure that will work for me, and if it would, I'm not sure how this would look or be configured.
If you are making your $http calls from a data service, you can set toggles in your service. Don't even make the http call if you know it will fail. Alternatively you could probably even make a whole mock data service to use at dev time, and replace it with the actual service when your backend is ready, avoiding issues of dev code being there in production. This is one of the reasons people say you should never reference $http in controllers.
See the AngularJS Style Guide - Data Services for a better explanation than I could ever write.

Downsides using front-end frameworks for API handling? Performance and security

So, while practising all the new tech. Angular 2, AngularJS, Firebase, Loopback, NodeJS etc .. I'm kind of confused on some topics that people don't really talk about. It might go into too much detail, but I'll try to split it as much as I can.
Part 1 -- Performance
I like the approach of: MyApp (Web, Mobile, ..) --> API <-- Database
Okay, we perform API requests to the same server over HTTP which is slower, but for small projects this should be a non issue right? Or are there any other solutions for this matter?
I know they often just do: MyApp --> Framework <-- Database and add an API interface which calls the correct actions to get the necessary logic/data out to eg. a mobile app
-- End Part 1
Part 2 -- Security
So, assume we have an API up and running either with Lumen, LoopBack or anything else like a realtime Firebase database (not really an API). Then we can connect with it over HTTP requests via Angular, jQuery... If a user inspects our source code, they can easily see how we handle data in the backend. How can this be secured in a way that only the necessary applications have control over the API (OAuth2 ?) and also that we limit the insight of users into our API.
-- End Part 2
Thanks.
Okay, I thought, it's a "too broad" question, but actually, it has a short answer.
Performance
Irrelevant. If you gotta fetch data, you gotta fetch data. Be it API call or some custom action in your laravel code (or something). Same HTTP stuff.
Security
... where a user can check the source code of the API calls.
Security through obscurity doesn't work. Always consider that your client is compromised. Use proper authentication/authorization methods (OAuth and the like). So even if a malicious user knows (which he will) your api endpoint signatures (or whatever you were trying to hide), he can't abuse them.

RestAngular vs $http on calls that aren't strictly RESTful?

Is there any point in using RestAngular if most of my calls don't end up being the usual RESTful GET all, GET by id, PUT, POST, DELETE, etc?
I understand the beauty of it for RESTful, but am I wrong in not seeing the advantage when I end up having other methods in my controllers? (E.g. returning a Dto of multiple joined tables).
Obviously the fact that you don't have to type out the full url is still there, but that's addressed by a "baseUrl" constant when using $http.
There is some benefit in that you can inject pre and post processors for requests, but for the most part, I find your assumption correct that there is little benefit when dealing with not strictly restful endpoints.
I would also recommend that $http requests reside in services and not in your controllers.

Resources