Mirage Passthrough returns Response Object instead of JSON data returned from network call - fetch

I am getting an error:
Mirage: Your Ember app tried to GET 'http://localhost:3006/data.json',
but there was no route defined to handle this request.
Define a route that matches this path in your mirage/config.js file.
Did you forget to add your namespace?
So following the documentation of mirage i added this:
this.passthrough('http://localhost:3006/data.json');
Even though after adding passthrough, I am getting such Response instead of JSON Object returned from the network api call.
The Actual Request i am making is:
fetch(`${host}/data.json`)
.then(res => res.json())
.then(data => {
// my operation on data
});
The response i am getting is:
{bodyUsed: true
headers: Headers {map: {…}}
ok: true
status: 200
statusText: "OK"
type: "default"
url: "http://localhost:3006/data.json"
_bodyInit: null
_bodyText: ""}
But I am expecting:
{
"files":
{
"x": "any",
"a": "any",
"b": "any",
"c": "any"
}
}
I kept a debugger in Pretender.js which is sending the FakeRequest and there in its object, I see that FakeRequest has responseType="" and response as null. And somehow my responseText has value but that is not considered and response value is considered and receiving null.
Also there is a logic which is return saying
"response" in xhr ? xhr.response : xhr.responseText
In this case i have response property but its value is null. Hence according to the above condition it is returning xhr.response which is null
Thanks in Advance.

Related

How to test pact with null data

I am aware of that PACT expects provider data need to be in our control, but I am facing following situation
I have pact contract for multiple consumers, all have some mandatory attribute and some are optional attribute, but business logic suppress all the attribute which are having null value, but according to contract I would still be needing that value as null,
what should I do for it?
Edit 1:
i.e let's say below my contract looks
consumer sent request with below params:
{ "method": "GET", "path" : "/pathOfApi", "headers":{ "accept": "json" } }
Provider responds with below data:
{ "Status": 200,
"body" :[
{"country" : "string",
"countryId" :"string",
"postalcode": "string",
"addressLine1" :"string",
"addressLine2" : "string"
"customerName" : "string",
"customerId" : "string"
}
]
now not all customer has address line 2, now in production if addressLine 2 is null it won't be present in output of api, but for our contract field should be present with null
If your provider does not return a field, but the consumer is expecting null, then either the consumer needs to change their expectation (because it's incorrect) or the provider should update its implementation to return null values.
Just because a consumer asks for something doesn't mean you need to do it!
If in some instances the field is present and other it is not, you need to write two tests to cover each case. I'd suggest covering one case with all of the fields, and another with the minimum set of fields (see https://docs.pact.io/faq/#why-is-there-no-support-for-specifying-optional-attributes).

AWS AppSync - DeleteItem doesn't execute response mapping template

When attempting to delete an item using the following request mapping:
{
"version" : "2017-02-28",
"operation" : "DeleteItem",
"key" : {
"id": { "S" : "$ctx.args.id"},
"sortKey" : { "S" : "$ctx.args.sortKey"}
}
}
If the item exists it will process the result through the response template, however when the item does not exist the response template is never run.
Response template:
#set($ctx.result.status = "SUCCESS")
#set($ctx.result.message = "This was a success!")
$utils.toJson($ctx.result)
I am aware that when an item does not exist in Dynamo it will perform no action but I would expect that it would still process through the template.
Is there anything I am missing or is it impossible for AppSync to processed a DeleteItem request through the response mapping when the document does not exist?
This the expected execution behavior for the version of the template you are using (2017-02-28).
You can switch your request mapping template version to 2018-05-29 and your response mapping template will be executed, with the following characteristics:
If the datasource invocation result is null, the response mapping template is executed.
If the datasource invocation yields an error, it is now up to you to handle the error. The invocation error is accessible using $ctx.error.
The response mapping template evaluated result will always be placed inside the GraphQL response data block. You can also raise or append an error using $util.error() and $util.appendError() respectively.
More info https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-changelog.html#aws-appsync-resolver-mapping-template-version-2018-05-29
So for your example:
{
"version" : "2018-05-29", ## Note the new version
"operation" : "DeleteItem",
"key" : {
"id": { "S" : "$ctx.args.id"},
"sortKey" : { "S" : "$ctx.args.sortKey"}
}
}
and response template
#if ( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type)
#end
#set($ctx.result.status = "SUCCESS")
#set($ctx.result.message = "This was a success!")
$utils.toJson($ctx.result)

FileSaver.js is saving corrupt images

This was working fine and suddenly stopped working. I'm not sure what exactly changed.
I need to download multiple images via URLs.
I'm using the following code:
https://plnkr.co/edit/nsxgwmNYUAVBRaXgDYys?p=preview
$http({
method:"GET",
url:"imageurl"
}).then(function(response){
saveAs(new Blob([response.data]), "image.jpg");
},function(err){
});
The files have different sizes, they are not 0 bytes.
For others coming here, check this solution.
What needed to be done was to add responseType: "blob" to the request:
$http({
method:"GET",
url:"imageurl",
responseType: "blob"
})
.then(...)
Here is the documentation for the responseType valid values, where it says the default is "" so the response is treated as text:
"": An empty responseType string is treated the same as "text", the default type (therefore, as a DOMString).
"blob:": The response is a Blob object containing the binary data.
Following code worked for me:
axios.get(`http://localhost:61078/api/values`, {
responseType: 'blob',
}).then(response => {
if (response) {
var FileSaver = require('file-saver');
FileSaver.saveAs(new Blob([response.data]), "image.png");
}
});

Managing API calls with default error handling in react-redux application

I've completed my application and I'm now integrating the real api calls for each async action. I use redux-thunk which returns a promise from an axios instance.
Currently I'm repeating so much of the same logic in my actions that I'm sure I'm missing something.
API response example
{
"ok": true,
"warnings": [],
"errors": [],
"response": {/* stuff */}
}
The Idea is that I need the same error handling if either the axios call fails (so another response status then 2xx). Additionally I need to also do the same thing when the api response returns "ok": false.
Preferably I would like to dispatch an action which shows a notification to users so they also know when something goes wrong. Aside from that I want to log the api response's warnings and error entities. This is mainly because I'll use sentry for monitoring.
Any Ideas on how to do this without doing a .catch() with the same logic on each api call in any of my action creators?
I've thought about using the onError of axios but that can't dispatch an action as far as I know.
You could use a response interceptor to dispatch appropriate actions. Just wire them up after you create the store
const store = createStore(...)
axios.interceptors.response.use((response) => {
if (!response.data.ok) {
store.dispatch({ type: "RESPONSE_NOT_OK", response }
}
return response
}, (error) => {
store.dispatch({ type: "RESPONSE_HAD_ERROR", error }
return Promise.reject(error)
})
Obviously, you can handle the response how ever you want, this was just for demonstration purposes.

How to include User-Agent info in a Meteor.http.call? MediaWiki requires it

Whenever I call the below method (CoffeeScript) that is on the server I get "Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice" from Wikipedia. How do I include user-agent info in the call? Or does it grab this from Meteor Accounts (which I'm not using yet)? thank you for any help...
Meteor.methods
wpSearch: (queryStr) ->
result = Meteor.http.call "GET", "http://en.wikipedia.org/w/api.php",
params:
action: "query"
list: "search"
format: "json"
srwhat: "text"
srsearch: queryStr
To clarify the previous answer for future visitors, the syntax for Meteor.http.get is as follows:
result = Meteor.http.get("https://api.github.com/user", {
headers: {
"User-Agent": "Meteor/1.0"
},
params: {
access_token: accessToken
}
});
Note the curly braces around the headers option and the comma afterwards separating the headers and params options (it's a syntax error without these things). This is example is part of the EventedMind how-to to customize the loginButtons during the onCreateUser() callback.
Just set User-Agent in the headers parameter (see http://docs.meteor.com/#meteor_http)
Meteor.methods
wpSearch: (queryStr) ->
result = Meteor.http.call "GET", "http://en.wikipedia.org/w/api.php",
headers:
"User-Agent": "Meteor/1.0"
params:
action: "query"
list: "search"
format: "json"
srwhat: "text"
srsearch: queryStr

Resources