FullCalendar fetch events foreach resource - ajax

The system I currently have setup stores events and resources on the backend, with an association between them. But, the only way to get events from the API is by resource. So I can't just get all events on this date, I need to specify what resource I want to get the events from.
In fullcalendar, I'm using resources and events as functions to make ajax calls to get the data. That's fine for the resources, I can just get them. But when I need to get the events, I need to make multiple ajax calls, one for each resource. Here's some psudocode
var timeline = new Calendar(timelineEl,{
initialView: 'resourceTimeline',
resources: function(fetchInfo, successCallback, failureCallback){
...
//ajax call to get resources
...
},
events: function(fetchInfo, successCallback, failureCallback){
/* pseudo code
list allEvents
foreach resource (gotten above)
ajax get events for that resource
establish association between events and that resource for FC backend
add events to allEvents list
save all events
*/
}
};
As far as I can tell, there isn't a simple way to get get all the resources in the event fetching method to do it this way.
What is the best way to do this then?
EDIT:
Thank you ADyson for letting me know what I was asking for wasn't clear. I'll try to better explain.
I need to make multiple ajax calls to get all of the events. I will need to get all of the events by resource, because that's how the backend is set up. The issue is that in the getEvents function that makes all those ajax calls, I need a way to check all the resources that are already in the calendar, so I can make all the calls. But I haven't been able to find a way to do that cleanly. I have managed to get something working, which I will put here when it's finished. But I don't love how I've done it so I still wanted to ask if anyone else had a better way.

Related

How to distinguish two responses that have the same status code but different response body?

I have an application where users can take part of puzzle solving events. I have an API endpoint /events/{id} that is used to get data associated to a certain event.
Based on whether the event has ended, the response will differ:
If the event has ended, the endpoint will return event name, participants, scores etc. with status code 200
If the event has not ended, the endpoint will return event name, start time, end time, puzzles etc. with status code 200.
On the client-side, what is the best way to distinguish these two responses from each other to decide which page to display, results page or event page? Is this a good way to accomplish my goal?
Some might answer that I should already know on the client-side whether the event has ended and then query for data accordingly. But what if user uses the address bar to navigate to an event? Then I will have no data to know, whether it truly has ended. I wouldn't like to first make an API call to know that it has (not) ended and then make another one for results/puzzles.
pass a boolean isFinished and return it inside of response object. If your response object is already defined, create a wrapper that has the previous response dto and a boolean flag.
Also we did use a solution like this in one of our projects at work for a big company so I would say it is somewhat industry accepted way of doing it.

Send notifications from one laravel app to another

I have two different Laravel 5.4 apps, a restaurant menu system to recieve and manage orders, and one website from where customer can place their orders. Both apps run on different server(localy), which means, in my (windows)system I can run only one app at a time(localhost:8000). Both are using the same database tables. My question is how can I notify the restaurant menu system when user places an order from the website i.e., adding new row to Orders table in db? I need a notification as well as auto generate new row in the table like here:
Restaurant Menu System . I have tried doing it with JQuery Ajax, but failed as there is nothing to trigger the ajax function in order page. Tried JQuery setInterval() from here but it seems like a very inefficient way and also gives an error of Uncaught SyntaxError: Invalid or unexpected token. I want to be as smooth as Facebook notifications. Is there any package or trick to do it?
The website looks just like any other ecommerce website with a cart and checkout system from where user can pay and place orders. Any leads is appreciated.
You have two options that I can think of.
One is a technique called comet which I believe Facebook uses or at least used at one point. It basically opens an ajax connection with your server and your server will occasionally check to see if there are any changes, in your case new orders, and when there is, will respond to the request appropriately. A very basic version of what that might look like is...
while (true) {
$order = Order::where('new', 1)->first();
if ($order !== null) {
$order->new = 0;
$order->save();
return $order;
}
sleep(5); // However long you want it to sleep for each time it checks
}
When you open up an ajax connection to this, it's just going to wait for the server to respond. When an order is made and the server finally does respond, your ajax function will get a response and you will need to do two things.
Show the order and do whatever other processing you want to do on it
Re-open the connection which will start the waiting process again
The disadvantage to this approach is it's still basically the setInterval approach except you've moved that logic to the server. It is more efficient this way because the biggest issue is it's just a single request instead of many so maybe not a big deal. The advantage is it's really easy.
The second way is a little bit more work I think but it would be even more efficient.
https://laravel.com/docs/5.4/broadcasting
You'd probably have to setup an event on your orders table so whenever anything is created there, it would use broadcasting to reach out to whatever javascript code you have setup to manage that.

Tracking ajax request status in a Flux application

We're refactoring a large Backbone application to use Flux to help solve some tight coupling and event / data flow issues. However, we haven't yet figured out how to handle cases where we need to know the status of a specific ajax request
When a controller component requests some data from a flux store, and that data has not yet been loaded, we trigger an ajax request to fetch the data. We dispatch one action when the request is initiated, and another on success or failure.
This is sufficient to load the correct data, and update the stores once the data has been loaded. But, we have some cases where we need to know whether a certain ajax request is pending or completed - sometimes just to display a spinner in one or more views, or sometimes to block other actions until the data is loaded.
Are there any patterns that people are using for this sort of behavior in flux/react apps? here are a few approaches I've considered:
Have a 'request status' store that knows whether there is a pending, completed, or failed request of any type. This works well for simple cases like 'is there a pending request for workout data', but becomes complicated if we want to get more granular 'is there a pending request for workout id 123'
Have all of the stores track whether the relevant data requests are pending or not, and return that status data as part of the store api - i.e. WorkoutStore.getWorkout would return something like { status: 'pending', data: {} }. The problem with this approach is that it seems like this sort of state shouldn't be mixed in with the domain data as it's really a separate concern. Also, now every consumer of the workout store api needs to handle this 'response with status' instead of just the relevant domain data
Ignore request status - either the data is there and the controller/view act on it, or the data isn't there and the controller/view don't act on it. Simpler, but probably not sufficient for our purposes
The solutions to this problem vary quite a bit based on the needs of the application, and I can't say that I know of a one-size-fits-all solution.
Often, #3 is fine, and your React components simply decide whether to show a spinner based on whether a prop is null.
When you need better tracking of requests, you may need this tracking at the level of the request itself, or you might instead need this at the level of the data that is being updated. These are two different needs that require similar, but slightly different approaches. Both solutions use a client-side id to track the request, like you have described in #1.
If the component that calls the action creator needs to know the state of the request, you create a requestID and hang on to that in this.state. Later, the component will examine a collection of requests passed down through props to see if the requestID is present as a key. If so, it can read the request status there, and clear the state. A RequestStore sounds like a fine place to store and manage that state.
However, if you need to know the status of the request at the level of a particular record, one way to manage this is to have your records in the store hold on to both a clientID and a more canonical (server-side) id. This way you can create the clientID as part of an optimistic update, and when the response comes back from the server, you can clear the clientID.
Another solution that we've been using on a few projects at Facebook is to create an action queue as an adjunct to the store. The action queue is a second storage area. All of your getters draw from both the store itself and the data in the action queue. So your optimistic updates don't actually update the store until the response comes back from the server.

Why use event listeners over function calls?

I've been studying event listeners lately and I think I've finally gotten them down. Basically, they are functions that are called on another object's method. My question is, why create an event listener when calling the function will work just fine?
Example, I want to call player.display_health(), and when this is fired, the method player.get_health() should be fired and stored so that display_health() has access to it. Why should I use an event listener over simply calling the function? Even if display_health() were in another object, this still doesn't appear to be a problem to me.
If you have another example that fits the usage better, please let me know. Perhaps particular languages don't benefit from it as much? (Javascript, PHP, ASP?)
You might not always be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code. In cases like that, it's better for the code to fire an event and allow the code you do control, or the code that should have the dependency, to listen for the event and act accordingly.
For example, perhaps you're creating a library that will be used by other people. They don't have the source code or in some way can't/shouldn't be able to modify it (or shouldn't have to). Your documentation states that specific events are raised under specific circumstances. They can then, in turn, respond to those events.
Or perhaps you have some domain libraries in your enterprise. You do control them and can modify them, but architecturally they're generally considered to be working as they currently are coded and shouldn't be changed. (Don't want to incur a round of QA to re-validate the updated code, the code belongs to another department and they don't want you to change it, etc.) And you're in the position where you want that code to be able to do different things in different circumstances/environments. If that code raises and event where relevant, you can hook your code into it (and/or swap out accordingly) without having to mess with that code.
Just a couple quick examples, I'm sure others have more.
My question is, why create an event listener when calling the function will work just fine?
What if you don't know what function you want to call?
Take the classic example, a Button that the user can click on. Whoever writes the library has no idea what function you want called when the button is clicked. It would also be pretty prohibitive if every Button could only call the same function when it is clicked.
So instead, you can attach an event handler to the event. Then when the event is triggered, the Button can do what it needs to, without having to know at compile-time exactly what function it's supposed to be calling.
In Brief, you can write the code without event listener, but using event listener help other to use the same code as library.
Even with the detailed answers above, I was still having trouble understanding what the actual difference was between using a controller / functions OR an event listener.
One of the things that has been left out in all of these answers is that the use of Events and Event Listeners comes in handy when you do not want to couple your code so closely. Each function, class, etc, should have singleness of purpose.
So say you are getting hit with an API request from an outsider. In my case, my exact problem understanding this concept was when I am receiving API calls from Stripe Webhooks.
The purpose of Stripe Webhooks is: say a customer spends $10,000 on your website. Your standard procedure is to Auth and Capture. Update DB to reflect their new membership status. In a perfect world, and in our company's case, 999/1000 times, this goes perfectly. Either their card is declined on the spot, or the payment goes through. In both cases, we send them an email letting them know.
But what about the 1/1000 time when the user pays and Stripe returns a Card Failure error (which can be a number of different things)? In our case, we email them and tell them the billing has failed. The problem we've encountered is that some BANKS are investigating large charges, which comes back as an Error, but then a few minutes later the bank authorizes the charges and the payment is captured.
So what is there to do? Enter Stripe Webhooks. Stripe Webhooks will hit an API endpoint if something like this occurs. Actually, Stripe Webhooks can hit your API any and every time a payment isn't instantly Authed, Captured, or if the customer asks for a refund.
This is where an Event Listener comes in handy. Stripe shoots over a POST with the customer info, as well as the Webhook type. We will now process that, update the database, and shoot them a success email.
But why not just use a standard route and controller?
The reason we don't just use a standard route and controller is because we would either need to modify the already defined functions, classes, etc, or create a new series of classes that are coupled together, such as -> Stripe API Calls Received, Update DB, Send Email. Instead of coupling these closely together, we use an Event Listener to first accept the API Call, then hit each of those Classes, Functions, etc., leaving everything uncoupled.
I looked everywhere, and I think the Laravel documentation explains it best. I finally understood when given a concrete example, and what the purpose of an Event Listener is:
Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.
https://laravel.com/docs/5.6/events
I think the main reason for events vs function calls is that events are 'listened to' while calls are 'made'. So a function call is always made to another object whereas listeners 'choose' to listen for an event to be broadcast from your object.
The observer pattern is a good study for this capability. Here is a brief node.js example which illustrates the concept:
var events = require('events');
var Person = function(pname) {
var name = pname;
};
var james = new Person('james');
var mary = new Person('mary');
var loudmouth = new Person('blabberer');
loudmouth.mouth = new events.EventEmitter();
//jame's observer.
james.read_lips = function(msg){
console.log("james found out: " + msg);
};
//james adds his event to the emitter's event listener.
james.enter_elevator = function(){
console.log('james is in the elevator');
//NOTE: james adds HIMSELF as a listener for the events that may
//transpire while he is in the elevator.
loudmouth.mouth.on('elevator gossip', james.read_lips)
};
//james removes his event from the emitter when he leaves the elevator.
james.leave_elevator = function(){
// read lips is how james responds to the event.
loudmouth.mouth.removeListener('elevator gossip', james.read_lips);
console.log('james has left the elevator');
};
//mary's observer
mary.overhear = function(msg){
console.log("mary heard: " + msg);
};
//mary adds her observer event to the emitter's event listeners
mary.enter_elevator = function(){
// overhear is how mary responds to the event.
console.log('mary is in the elevator');
//NOTE: now mary adds HERSELF to the listeners in the elevator and
//she observes using a different method than james which suits her.
loudmouth.mouth.on('elevator gossip', mary.overhear);
};
loudmouth.speaks = function(what_is_said){
console.log('loudmouth: ' + what_is_said);
this.mouth.emit('elevator gossip', what_is_said);
};
james.enter_elevator();
mary.enter_elevator();
loudmouth.speaks('boss is having an affair');
james.leave_elevator();
loudmouth.speaks('just kidding');
console.log('james did not hear the last line because he was not listening anymore =)');
so in this 'story' the actors choose to listen or when to not listen for events from a third party. I hope this helps.

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

Resources