Is it possible to cancel Breeze requests (AngularJS)? - javascript

I'm trying to find a way to cancel BreezeJS queries for the purpose of implementing a live search that queries BreezeJS on keypress (see my other question).
I know that in Angular, $http requests can be cancelled by passing a promise to the timeout parameter in the config object, and then calling resolve() on that promise.
I also know that I can get BreezeJS to use my module's $http insance with:
var ajax = breeze.config.initializeAdapterInstance('ajax', 'angular');
ajax.setHttp($http);
So I was thinking about possibly creating a request interceptor on $http that would set config.timeout to a promise. But that still leaves me quite a few steps away from solving the problem, because I would somehow need to be able to give the promise to my interceptor from the code running the query (so that the querying code could resolve() the promise if needed).
Is there a better way? Is it even possible?

Update 16 May 2014
You can set HTTP-level timeout and cancellation with the AJAX Adapter's requestInterceptor as of v.1.4.12. See the documentation, "Controlling AJAX calls".
Original answer
The EntityManager HTTP service operations don't offer cancel or timeout options. Maybe they will someday.
The v.1.4.11 Breeze AJAX adapters don't offer cancel or timeout options either. But they will in v.1.4.12 and you can see the preview on github right now.
The samples on github illustrate both cancel and timeout with the new adapters. For users of the jQuery AJAX component there is DocCode:jQueryAjaxAdapterTests.js. For users of Angular's $http there is the Zza-Node-Mongo:ajax-adapter.async.spec.js.
It's best if you can run the samples but if you can't (perhaps because you don't use one of the technologies involved), the test files (see links above) are easy to read and you should glean the ideas that will help. At least I hope so.
Usage
Cancel and timeout are useful features. Do you need them for your use case? Maybe. But you'd want to take a first step of de-bouncing the text that users enter into your "live search" so that you aren't firing off 100s of pointless queries.
That observation is discussed in your related StackOverflow question.

Related

What is the proper algo/method to track changes between two async calls/requests

I have frontend that send requests to backend to keep the data as "live" as possible. The problem is that if frontend sends two different(in terms of data) requests in a short period of time, server may get the second request before the first one(due to delay, bad network, async etc).
My question is there any type of algorithm/method to deal with such events, to track changes in a sync way for async requests?
I thought of timestamps, but in that case I would need to "trust" the client - doesn't look a good solution.
I can't share my code(not sure if it's going to help anyway) or give you exactly what I'm making, but it's kind of live-text-editor, when two(or more) parties can see the editor and make changes to it.
Also, even though I would prefer not to use web-sockets, but perhaps web-sockets could solve this problem(never used it before)? I don't know how web-sockets work especially with asynchronous calls.
I use MERN stack, in case it's relevant.

Multiple fetch buttons and AbortController

I'm new to Svelte and learning it for self-education.
I'm trying to implement very basic scenario:
there are multiple buttons on the page, each button fetches some data and displays result in the same area.
To make sure that due to the different network response timings later result will not be overwritten by old request I want to abort all previous fetches.
Here is the REPL I've made so far: https://svelte.dev/repl/c763e1814da740f186620d75ad1fa42f?version=3.38.2
Question: why request aborted in advance and how to correct this?
(Any advises how to make my Svelte code styling better will be much appreciated, I suspect this logic can be implemented in much better/efficient way)
It's the AbortController. Once abort() is called it stays in the aborted state. I looked for some references but couldn't find any documentation that states this explicitly. However, a bit of trial and error seems to prove this. You need to create a new AbortController after calling abort().

Send scenario result in after scenario hook to external endpoint [duplicate]

This question already has answers here:
Dynamic scenario freezes when called using afterFeature hook
(2 answers)
Closed 1 year ago.
I want a common implementation to write the: request-body, request-method & response-body to an output file for all the HTTP requests that I make in any of the karate feature files.
I have read through the documentation, and the closest option that I found was the afterScenario hook. However this doesn't help me in cases where I want to make multiple API calls in the same scenario.
I also tried using karate.prevRequest object by passing it to java function that I wrote. While this helps me capture the information that I want, I have to keep calling my java function after every API call, which I don't want to do.
I want to be able to write a hook that gets called after every API call and gives me access to request-body, request-headers, response-headers, response-body, request-method and request URL.
This should be fairly straight forward, clearly I seem to be missing something here.
First, I personally think that this is a mis-use of Karate, and you seem to be more interested in reports than actually doing testing. Take some time to think about it. Karate has excellent report integration and you are just wasting your time doing this in my very honest, sincere opinion. No one has asked for this.
Anyway. There is a new ExecutionHook in 0.9.5.RC4, details here: https://github.com/intuit/karate/issues/970#issuecomment-557443551
You can implement afterStep, see if it is a method step and then do this. If you need changes, open an issue. Also see: https://stackoverflow.com/a/60944060/143475
EDIT: just remembered - in the develop branch we added a way to intercept all requests and responses: https://twitter.com/karatedsl/status/1195240779213496320 - will be happy to get your feedback and see if we can merge this concept with the above hook - or improve the interfaces if needed
EDIT: in many cases, the afterScenario may be sufficient, note that you can call any Karate feature, which means you can do HTTP requests: https://stackoverflow.com/a/51467470/143475
EDIT - the hooks API has changed for 1.0: https://github.com/intuit/karate/wiki/1.0-upgrade-guide
The ExecutionHook supports quite a lot different use cases.
Steps can be aborted or changed
Request and Response can be sniffed
See ExecutionHookExampleTest on how to use an ExecutionHook.
The API has changed. With karate version 1.1.0 (correct me, if I'm wrong)
It's now com.intuit.karate.RuntimeHook and you can use
com.intuit.karate.Runner.Builder#hook or
com.intuit.karate.Runner.Builder#hooks
method to add a hook to your karate test case execution.

When making multiple ajax requests, is there a "good pattern" for tracking which data the responses line up with?

I build a lot of client-side js apps and have worked mostly with Backbone. Backbone always expects your api to return a copy of the created/changed/deleted model when such ajax actions are completed, allowing it to easily determine which "model" just got updated.
I'm working in a new scenario (new framework, freshly built API) in which all I get back from the API are success/error status codes. The whole "return the entire model" seems like a crutch...but the more I work trying to keep track of these async actions the more it feels like a necessary one.
Is there some kind of convention (outside of the Backbone world, perhaps) for more easily handling this kind of thing?
Edit: I may want to point out I'm using FLUX so the uni-directional flow is preventing me from just cross-wiring everything on either side of the dispatcher.
Your question title is more clear to me than the description, so I'll go with that.
If you are having difficulties in keeping track of multiple ajax requests results, you should use Promises.
For example, with the Q library you can do something like this:
Q.all([AjaxModel1(), AjaxModel2(), AjaxModel3()])
.spread(function(resultModel1, resultModel2, resultModel3) {
});
If what you need to know is how to get a model every time you make a change to them, I would need more details about your framework/server/code.

JavaScript Request/Operation Framework or Toolkit?

I'm building a complex application in JavaScript which needs to make several requests to the server. Sometimes that request cannot be completed as sent, and addition information is needed. I would like the ability to have the server inform the application in the request's response that more information is needed and to describe how to retrieve that information.
For example, say a user tries to perform an operation that his current permissions level does not allow. The server needs to ask the application for an override authorization code, basically meaning the application needs to pop up with a dialog asking for an admin passcode.
I'd like to have some kind of framework that abstracts all this. Possible a main "Request" or "Operation" class, which I can define sub-Request classes that define possible interpretations of requests. I'm not sure if something like this exists already or not.
So I guess my questions are: 1) Does a framework like this exists? and 2) Are there any articles on this topic (platform and language agnostic, I can learn how they work from any source). I know frameworks like Dojo and ExtJS use something like it for their data stores, but I'm not sure if it's exactly what i'm needing, or how it even works for that matter.
Any help leading me in the right direction is appreciated, Thank You.
EDIT:
A point should be made I am looking for something that is abstract from the technology used to actually send that data to the server. That way I could utilize the same framework on different ajax technologies.
Basically I'm looking for a framework or article that can help me figure out how to create a custom "Application Protocol". An example of this would be:
{
type: 512,
success: true,
data: { some: "data" }
}
I know I have to design the protocol itself, but what I need help with is creating a "class" or something that interprets this protocol automatically instead of just making redundant onSuccess callbacks
I have worked on an open source project named Pomegranate Framework which does what you want (to some extent). Perhaps you can extend it in order to meet your needs. It comes with an application layer close to want you asked for but you need to implement your protocol as it fits. Here's its address:
Pomegranate Framework
I haven't found the time to document it yet but it comes with a bunch of examples that may be useful to you. You may also want to take a look at its example page:
Pomegranate Framework Examples
I think you would like to see the 021 example titled "Handling server errors in client". I hope it's what you are looking for.
Use Dojo and jQuery's Deferred object for callbacks. It is an implementation of the Promise design pattern. Every action has a success callback chain and a failure callback chain and both chains can diverge or merge at various points along the chains and chains can branch off to create sub-deferreds.
If you know the state of your application on the client (and there are only a few error causes and you do not need detailed information from the server), you can and should use HTTP status codes. As far as I know 200 is the only one with a body, so you can't (or shouldn't, there's always adding headers, but I'd stay clear of that path) transmit anything else - but every framework should provide you with the means to pass an error handler on sending a request. In the callback function you pass as an error handler, you just have to do whatever the respective status calls for.
It's supported by the protocol, independent of whether you pass HTML, JSON or anything else and error callbacks based on the status code are supported by every library worth using.
Since you're basically talking about "server-sided push events", you need some technique that allows your server script to send data to your clients.
There are some well knowns methods like COMET, Flash Sockets and the latest guy in town WebSockets around.
Since WebSockets is probably the most sophisticated stuff from all of these, you should aim for that. Unfortunately, its browser support is limited to the "latest version" for most browsers, if you're good with that, just use them right away. If you want some fallbacks for older browsers, the most used framework for that should be socket.IO.
But even socketIO only abstracts all the different communication techniques away for you. Anyway, it should be fairly easy to build a solid management framework around that by yourself. So my answer on that part is, I'm not aware of any library or framework which deals with that kind of stuff.
There are various ways to achieve this using ExtJs.
The most bare-bone one is to use Ext.Ajax.request() providing url, params, method. Then in your success handler, check for the server response and if it requires an additional data from the user - display an extra credentials dialog, and send another request with the extra credentials details that will unlock the server side script.
Notice that the success hander of the request method gives you back the config object of the request in its options parameter, so you can quite easily call the same request again, only adding the extra credentials this time around.
Here's a jsfiddle code demonstrating this concept (I've shown both using success and a global handler for all calls - I hope you'll be able to work out how to take it from here). And a similar one, which I believe is more what you're after exactly.
I'll be happy to help further, just ask the questions.
If abstraction and testability is what you want, I highly recommend AngularJS. angular $q which is an implementation of Kris Kowal's Q. You can create services that will hide away how you call the server and will allow you to change server implentations in future will little grief.
It will look like problem of server push i.e. wherever change occured data will be pushed to client There are following options
reverse AJAX by DWR Framework.
Ajax Push Engine http://www.ape-project.org/
Commercial
WebSync
You can use long polling mechanism like this
(
function poll(){
$.ajax({ url: "server", success: function(data){
myobject.setValue(data.value);
}, dataType: "json", complete: poll, timeout: 30000 });
})();
You will get more info at ajax push server

Categories

Resources