-
Notifications
You must be signed in to change notification settings - Fork 1
2.3 Lunar.createProxy
"In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes.". Lunar's Proxy is an optional layer that you can .create in order to add middlewares to your module's calls.
When you call this method, the Lunar function should receive the object that you want to transform in a Proxy. And the createProxy method should receive the destination module (that you have previously created with .createModule).
import Lunar from 'lunarjs';
import Home from '/lunar/home';
angular.module('app.home')
.service('HomeService', HomeService);
/*@ngInject*/
function HomeService($http) {
Lunar(this).createProxy(Home);
//...
this.addMiddleware({
action: Home.actions.FORMAT_TITLE,
before: function(data) {
return $http({
method: 'GET',
url: 'http://localhost:4000/posts'
});
}
});
}In the above example, we passed the Angular's Service as a parameter to Lunar, and created a Proxy on top of the Home module. When you do that, the original Angular's Service will have on its "this":
- addMiddleware(middleware)
- Proxy.actions
- Proxy.doAction
The Proxy object is internal and you shouldn't have to call it. It is just for internal reference. The Proxy.doAction for example, is the method internally called by the Activator request method, and the one who will handle before and after middlewares and catch errors. When called, it will eventually call the Mediator to find the correct "action method" from your Module.
The middleware parameter is an object that contains:
- The action you want to intercept.
- A before method that gets executed before the action call and its result becomes the parameter of your called action.
- An after method that gets executed after the action call and its result becomes the parameter of your final callback.
{
action: Home.actions.FORMAT_TITLE,
before: function(data) {
return $http({
method: 'GET',
url: 'http://localhost:4000/posts'
});
},
after: function(data) {
return data.replace('...','');
}
}When a request is made from an Activator, the Proxy will execute the before middleware; check for any errors; return the Promise result if it is the case; and send the result as a parameter to your Module "action method". The return from your "action method" will then be passed to the after middleware (if there is one); if it is a Promise, the result will be passed; and the result of your after middleware will be the final response as a Promise with "success" and "error" callbacks.