Ember network call payload behind one call - ember.js

I am sending a network call using ember.js
The event is triggered by a check box click that adds or removes an item from an array called features.
Currently if I click on the checkbox to add "edit users" to the array, the features array is updated and the update method in my account_owner model is triggered.
The users object is passed in to the update method and when I log user.features the array has all three items including the one that was just added.
before sending to the network I create a payload object that looks like:
payload: { features: ["employee advocacy", "other", "edit_users"]}
Here is my update method
update(user) {
var payload = {
features: user.features
};
console.log("###payload", payload)
console.log("###this.accountID", this.accountID)
const url = `/api/accounts/${this.id}/account_owners/${this.id}`;
return put(url, payload).then(() => this);
},
When this sends to the network only 2 of the three features are sent.
the paylod looks like:
payload: { features: ["employee advocacy", "other"]}
The thing is if I click the edit users check box again, edit_users is removed from the features array as well as the payload in the method when I log it but when the call is sent to the network all three items including edit_users show up in the payload. like this:
payload: { features: ["employee advocacy", "other", "edit_users"]}
It seems like data in the network call is behind one click but I can not figure out why this is working this way.

Related

How to get PayPal client-side info to Django?

I am using PayPal standard IPN payment solution in client side in my Django web app.
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
});
}
}).render('#paypal-button-container');
</script>
</body>
everything works fine and I can access all the data through the details variable in the js code.
Now, i need to insert the details into django db, no api, simple model.
Tried many things, none worked.
I prefer not to use django-paypal because it doesn't have smart buttons (as far as i saw) and there is only option for "buy now button" and no credit / debit card.
how can it be done? or is there smart buttons for django-paypal package?
Thanks for the help!
How to get PayPal client-side info to Django?
Don't.
An integration that creates and captures payments with client-side JS functions is for very simple use cases. It should never be used if you need to do anything automated with the result, such as writing transaction results to a database.
Instead, API-based integrations exist for precisely this use case. Use the v2/checkout/orders API and make two routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You could use the Checkout-PHP-SDK for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. Both of these routes should return/output only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as reserving product or sending an email) immediately before forwarding return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases.
Pair those 2 routes with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object)

Ember save data to store and display without having a server api

I have a users model which fetches data from github users api (https://api.github.com/users). While displaying the list there is a add button which should add the user to a shortlist section below and which has a remove button to remove user from shortlist. I don't have api to save shortlist data. What is the best approach to make this work?
Try 1: Created a shortlist model and used store.push
this.store.push({
data: [{
id: user.id,
type: 'shortlist',
attributes: {
login: userData.login,
avatar_url: userData.avatar_url,
type: userData.type
}
}]
});
and used item.unloadRecord(); to remove from model. But did nor found a way to fetch all record and show as this.store.peakAll('shortlist') wasen't working.
Try 2: Used localstorage to add user to shortlist, display and remove but here it needs page reload to display the add/remove changes as i used setupController to get the items from localstorage.
Please suggest how to do this in best possible way.

ASP.Net Core 2.0 API Response hangs with large json payload

I am working on an ASP Net Core 2.0 Web API. One of my endpoints returns a json object that includes a text field that can be fairly large. When this field gets around 10Mb in size the controller just stops until the timeout is hit. When I debug, I see that the json object is created in my business logic and passed to the endpoint controller but the controller just stops right after it receives json object with no error and doesn't return to the caller until the request finally times out. I increased my requestTimeout to 20 mins even though the business logic generates the json object in less than 2 minutes. It just hangs until the 20 minute timeout is hit.
Here is my controller action;
[EXAMPLE 1]
[HttpGet(Name = "GetFile")]
public async Task<FileResponseDto> GetFile([FromRoute] int companyId, [FromRoute] int siteId, [FromRoute] int FileId,
[FromHeader(Name = "Accept")] string mediaType, CancellationToken cancellationToken)
{
var fileResponseDto = _fileBll.GetFile(companyId, siteId, fileId, HttpContext);
// This is the point where the controller appears to hang
return await Task.Factory.StartNew(() => fileResponseDto, cancellationToken);
}
and my DTO object;
public class FileResponseDto
{
public string ReferenceId { get; set; }
public string Filename { get; set; }
public string ProcessingFile { get; set; }
}
The property that is the large string is the ProcessingFile property in the FileResponseDto class.
This works fine until my ProcessingFile property gets to around 30K lines (about 10Mb) and then the controller just hangs after it completes the line;
var fileResponseDto = _fileBll.GetFile(companyId, siteId, fileId, HttpContext);
At this point, my assumption was that I have hit some limitation in the size of the json object. So, to test, I changed my controller so that it returns a file instead, like what is shown below;
[EXAMPLE 2]
[HttpGet(Name = "GetFile")]
public async Task<FileContentResults> GetFile([FromRoute] int companyId, [FromRoute] int siteId, [FromRoute] int fileId,
[FromHeader(Name = "Accept")] string mediaType, CancellationToken cancellationToken)
{
var fileResponseDto = _fileBll.GetFile(companyId, siteId, fileId, HttpContext);
var outputFile = Encoding.ASCII.GetBytes(fileResponseDto.ProcessingFile);
return await Task.Factory.StartNew(() =>
new FileContentResult(outputFile, new MediaTypeHeaderValue(MediaTypeNames.Application.Octet))
{
FileDownloadName = fileResponseDto.Filename
}, cancellationToken);
}
Making this change works and I can receive a file download dialog popup and a successful file if I select "Send and Download" in Postman.
So, this leads me to believe that there is something size related to the json object being transferred in the first example.
However, web searches have not turned up anything useful on this issue, which makes me think that perhaps I am missing something here.
I did find this link in StackOverflow and tried it by using...
var outfileJson = JsonConvert.SerializeObject<fileResponseDto>;
outfileJson.MaxJsonLength = Int32.MaxValue;
but outfileJson did not have a MasJsonLength property.
So.. any ideas?
EDIT 6/8/18
After 2 days, 22 views and no actual responses. I figured something must be wrong with my approach. I realized that I did not mention that I was performing these tests in Postman, which is where I was seeing the problem. After further digging, I found a post on GitHub that seemed to be related to what I was experiencing in Postman (the hang on large response payload). It seems that Postman has a limit in the number of "rows" it returns in the response. The GitHub post was a feature request to increase the number of rows.
I am not sure how to handle this StackOverflow question now. Since I didn't mention Postman in the original post, I don't feel right just answering my own question. So, I guess I will leave it as is for a couple of days to see if anyone chimes in with their thoughts before I do that.
As it turns out, the was, if fact, an issue with Postman and the size of the response payload it currently supports. If, instead of selecting Send, I select Send and Download in Postman, It will download the JSON object and pop up a dialog box to allow me to save it to my local drive. Then when I examine the file, I can see the json object is correctly formatted and transferred.
I confirmed that it was only a Postman issue and not a .NET HttpResponse issue by performing the API call in a .Net client application, which was able to receive the Json object without error.

How to handle race-condition in ember-data when live-polling filtered array and saving records

I have an Ember Route that polls for new records every 5 seconds.
Here is the Route's model function:
model: ->
#store.filter "event", "status": "created", (instance) =>
instance.get("status") == "created"
Here is the Route's polling mechanism:
setupController: (controller, model) ->
#_super(controller, model)
#startPolling() unless #get('polling')
startPolling: ->
#set('polling', true)
Ember.run.later #, ->
#poll()
, 5000
poll: ->
return unless #get('polling')
#model().then =>
#poller = Ember.run.later #, ->
#poll()
, 5000
This functionality works fine except in one scenario.
A user may alter the state attribute of an Event model.
For example, a user can choose to hide an Event instance, which calls the following code:
changeStatusAndDisplayFlash: (event, status) ->
event.set('status', status)
event.save().then (event) =>
#queueFlashMessage(event)
The problem is that if the Events poller is currently making a request and the individual record save promise returns before the poller's request completes, the record will have its state reverted when the poller's request finally does complete.
This is a classic race-condition, however, I am unsure of how to handle this in ember-data.
In short, I'm trying to figure out how to:
Honor the state of a model based on the most recently triggered request rather than the most recently completed request.
So if we have the following requests (in order of when they were initiated):
Original model request which returns the filtered collection.
Polling request that updates the filtered collection (with new models and/or updated attributes to existing models).
Save request that updates the attributes of a single model in the collection.
And the order of completion is such:
1, 3, 2
I would like the outcome of request #3 to be the final result, however, as it stands, the last request to complete (which is currently #2) is the one that sets the outcome.
Does anyone know of a strategy for achieving this in ember/ember-data?
Thank you for your time.

Partial updates to an SWF

Suppose all that happens initially in a client swf is a user clicks a hyperlink in a text object of the swf, so this requests a "page" from the server. In response the server just modifies that existing swf in the client browser, by for example (?) invoking public functions of it, and possibly passing in as parameters the name of image or data files which were also downloaded in response to the URL request. The crucial part is that all that can happen initially in the SWF is a URL "page" request. Is this commonly done and if so, how.
Clicking on an hyperlink in AS3 will trigger a TextEvent.LINK event, you can then listen to this event and in your function proceed to call the relevant service which in turn will send you a response which you can use to update your swf data.
Check the docs here for the TextEvent class
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/
Now, it all depends on what your link is, if it loads an XML ,then you can use the URLLoader class to load the XML data
private function init():void
{
var tf:TextField = new TextField();
tf.htmlText = "<a href='http://example.com/data.xml'>Update Data</a>";
tf.addEventListener(TextEvent.LINK, clickHandler);
addChild(tf);
}
private function clickHandler(e:TextEvent):void
{
trace(e.type); // link
trace(e.text); // http://example.com/data.xml
var loader:URLLoader = new URLLoader();
loader.addEventListener( Event.COMPLETE , dataLoaded );
loader.load( new URLRequest( e.text ) );
}
private function dataLoaded(event:Event):void
{
trace( event.target.data );// xml content
//from here you can then parse the XML & update your swf
}