Is there any way to create a hook that calls 2 different other hooks and then do a || between them?
I would like to call the authenticate('jwt') hook and if this one fails call a custom hook to see if the request is local (so I don't need authentication). If the second hook is positive, I'll go on with the request. If both fail, then it's a no go.
If I call the hooks one after another the first fails and so the service fails.
Can this be achieved or is there a better way to do this?
Thanks in advance
Using feathers-hooks-common you can do an iff chain, e.g.
const { iff, isProvider } = require('feathers-hooks-common');
module.exports = {
before: {
all: iff(isProvider('external'), authenticate('jwt')
}
}
Related
Is it possible to monitor the JS function and identify when it's completed? Example: I have a JS method that has a long process time, I would like to monitor the process or at least know when it's done.
There are a few ways to know when a function has finished running.
Synchronous Functions
If the function in question runs completely synchronously, then the code which called the function will wait until it is done before executing. For example:
function a() {
// do something
}
function b() {
a();
console.log("a is done"); // will only run once a is finished
}
Asynchronous Functions
Promises in JavaScript are another way to do this task, and they work even when you have asynchronous calls - e.g. requests to a server, etc. To get started, you make the first function return a promise:
function a() {
return new Promise((resolve, reject)=>{
// do something
resolve(); // once we're done, resolve the promise
});
}
The promise's constructor takes a function which takes two arguments, resolve and reject, which are given to it by JavaScript. You can call the resolve() function when you are done with processing, and the reject() function if you encounter some error which means you are unable to resolve.
To use this, you can do something like so:
function b() {
a().then(()=>{
console.log("a is done"); // will only run once a is finished
});
}
The nice thing about running a promise is that all other code can continue running - nothing is blocked behind the promise except the anonymous function which you pass into the then method. This is definitely the approach I would take for something like this.
Monitoring progress / logging
With regards to monitoring the progress of a function, it really depends on how the function works. Your best bet is probably to make calls to some sort of logging function whenever the long function reaches certain parts. For example:
function a() {
// do something
console.log("did something");
// do something else
console.log("done");
}
If you can't change function a() for whatever reason, there's no good way to do this (that I'm aware of), unless you know it changes some global variable and you can check that for changes, but an approach like that would be quite dodgy and definitely not a good way to do things.
Conclusion
There's not too much more that I can really say without knowing what kind of function / process it is that you want to monitor - there are special ways to check on file upload progress, for example, that I have not covered here.
Likewise, if the process is happening on a different server or device, these methods won't work at all - you'd likely need to check out WebSockets or (more likely) Server Sent Events to get progress updates for those tasks.
I am using redux-observable and in my epics I am changing the route in some of them using browserHistory.push. Is this standard/good practice? my gut feeling tells no, however need your opinion. In addition to this after upgrading to react-router 4, I cannot get access to browserHistory how do I do this?
Imperatively calling browserHistory.push() is totally fine. If it works for your use case and you don't need to know about the route changes in your reducers, carry on!
That said, the "purist" way would be for your epic to emit an action that will cause the route change. This can be done in react-router v4 by using the new react-router-redux, which supersedes the old one with the same name.
Once added, you can use the provided actions creators:
import { push } from 'react-router-redux';
export const somethingEpic = action$ =>
action$.ofType(SOMETHING)
.switchMap(() => {
somethingLikeAjaxOrWhatever()
.mergeMap(response => Observable.of(
somethingFulfilled(response),
push('/success-page')
))
});
To be clear, push() replace() etc in react-router-redux are action creators--aka action factories. They don't actually cause the route change themselves, or perform any side effects at all. They return an action that needs to be dispatched somehow for the route to change.
The other benefit of using actions to signal route change intents is testability. You no longer have to mock a history API, you can just assert that the epic emits the expected action. This is known as "effects as data", since your code doesn't perform the actual side effect, you just generate the intent.
Regarding redux -> in development mode I would like to "freeze" the object state after the reducers have done their work and before subscribers get notified...
My approach was to define middleware for "freezing" the state of the object (e.g. with node module deep-freeze-strict).
But it seems this is not the correct approach. Because of a subscriber receives the updated state before the freezing takes place...
Does anybody has an idea how to define such freezing before the subscribers are notified??
My solution for this was to define a function which wraps the reducers:
export function freezeStateOfReducer(reducer): any {
return (state, action) => {
let newState = reducer(state, action);
freezeState(newState);
return newState;
};
}
export const rootReducer = combineReducers({
firstReducer: ...
});
createStore(freezeStateOfReducer(rootReducer));
That's an interesting question, actually. In theory, the only state updates should be happening in the reducer. In practice, I've definitely seen cases where people were accidentally mutating things in their mapState functions. You're definitely right that subscribers are notified before the middleware sees the updated state.
This might be a valid use case for a store enhancer, which could ensure that the state is frozen before actually notifying subscribers. Or, a higher-order reducer that wraps around your normal root reducer.
Also, there are several existing "freeze state in development" utilities already out there. See the DevTools#Linting section of my Redux addons catalog for a list of those existing libs.
I search for a long time, but I still not found the answer.
In common case, we keep the token of a remote method call, Flex -> Java for example.
But, if the client know that the current call is not needed anymore, how stopping the server processing ?
With an asyncToken, is it possible to stop a remote call ?
Thanks for your answer.
As I understood it, an AsyncToken just provides extra data for some operation. You'll need to access that operation to cancel.
IF you're calling an HTTPService, you use the cancel() method.
If you're using a WebService, you should be able to call getOperation() method and then cancel() the corresponding operation.
If you're using a RemoteObject you should be able to call getOperation() method and then cancel() on the corresponding operation.
Currently working on a flex AIR project based on PureMVC framework. There was a new requirement to the project, an operation is to be performed repetitively at regular interval which has some business logic. As per PureMVC this should be placed in the command, but then command would get garbage collected the moment its executed.
Given the scenario there are few doubts/confusions/clarifications...
Creating a command with business logic would be one solution ... but then who would trigger it at specific interval? (shouldn't this be done by a command as per PureMVC)
Placing the command trigger in a mediator or placing the logic in a mediator (this would make pureMVC a bit impure :) )
How do I find a solution for this kind of scenario?
You need to pull apart the async process you want to run and the repetitive triggering of said process. My advice is to create a Proxy for the async process and a separate Proxy that's a wrapper for a Timer which simply sends a notification upon timeout. The notification is coupled to a command, which in turn calls the async proxy's methods. That way you can add logic to the command for instance what to do if the process is still busy.
The benefits of creating two proxies: you adhere to SRP. You can easily swap/modify/remove the timing proxy w/o touching the async proxy. Everything is nicely separated.
depends on what the Command should do - if it updates the Model put a Timer in one of your Proxy class and send a Notification every xx seconds which is mapped to a Command that does whatever it is you want it to do.
If it should just update the View you could add the Timer to the corresponding Mediator but then you wouldn't need a Command at all.
**
Don't create more Singletons than you need. ApplicationFacade is already one - try and keep it that way.
**
If you have to do any async calls to the backend, just make sure to add the EventListener without weakReference set to true - then everything should be ok...
Try this:
Create a Singleton class - singleton class in Flex
Have a function in this class (eg. called start) that when called starts a timer, the callback function of which sends a notification, that triggers a command that does your business logic.
When you are ready to start your regular actions simply call the get instance method on your singleton, to create the singleton and then call it's start() function.
*Optionally have a stop function that cancels the timer and stops the regular notifications being sent.
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
public final class RepititiveSingleton
{
private var timer:Timer;
private static var instance:RepititiveSingleton= new RepititiveSingleton();
public function RepititiveSingleton() {
if( RepititiveSingleton.instance ) {
throw new Error(
"ReptitiveSingleton can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():RepititiveSingleton{
return RepititiveSingleton.instance;
}
public function start(interval:Number = 1000):void {
timer = new Timer(interval);
timer.addEventListener(TimerEvent.TIMER, onTimer);
}
private function onTimer(e:TimerEvent):void {
ApplicationFacade.getInstance().sendNotification(Constants.REPTITIVE_ACTION_NOTIFICATION));
}
}
}
This code assumes that you have your Concrete facade named ApplicationFacade, and have registered a notification using a String constant that is referenced from a class called constants.
Then in an appropriate place (maybe in your startup command) you can add:
RepetitiveSingleton.getInstance().start();
Hope this helps you.
IMO, the timer belongs in a mediator. Let it- well, mediate the asynch process messaging. It will be a little state machine to make sure everything is running smoothly. Commands still do the heavy lifting, it just sits around like a 911 operator.