Amazon SP API download report document - amazon-mws

I'm trying to download report document from amazon SP API but couldn't figure out what should I do. Did everything they said in these link1 link2 link3 links and got same error from all these three.
error:
Error: incorrect header check
at Zlib.zlibOnError [as onerror] (node:zlib:189:17) {
errno: -3,
code: 'Z_DATA_ERROR'
}
Last tried code:
const res = await axios.get(
'mylink'
);
const payload = Buffer.from(res.data, 'base64');
const data = JSON.parse(pako.inflate(payload, { to: 'string' }));
console.log('first', data);

Related

How to specify HTTP response code in next.js

I have a Next.js v12 application written in TypeScript.
I have a _error.tsx page providing custom UI experience for various errors, including 410, 404 and other ones. The issue is, whatever API error triggers the appearance of this page on the server-side, the client browser GETs this page from server with the HTTP status code of 500.
How could I customize that status code, so that for example the page for 410 actually has the HTTP status code of 410?
Well, I managed to find the solution on my own.
It's a little bit counter-intuitive, but to get the desired behavior you should just directly set the value of statusCode of the res object coming into getInitialProps of the said _error.tsx page.
Along these lines:
ErrorPage.getInitialProps = ({ res, err }: NextPageContext) => {
const statusCode =
(err as AxiosError)?.response?.status ?? res?.statusCode ?? err?.statusCode ?? undefined;
if (res && statusCode) {
res.statusCode = statusCode;
}
const text = String(res?.statusMessage || err?.message || err);
return { statusCode, text };
};

Trying to upload files to firebase storage but its not working. Error object is empty, how do I figure out what's wrong?

So i'm trying to send image files uploaded by my users to firebase storage using the file type input element. Like this:
<input
className={inputStyle}
{...register("donorPhotoFile")}
type="file"
accept=".png, .jpg,.jpeg"
></input>
So when I try to console.log the value returned of that input, im getting an object with the following properties:
name: "file_name.jpg",
size: ,
type: "image/png"
webkitRelativePath: ""
The /api/firebase is my api endpoint in next.js to upload my form data to firestore. From the firebase documentation, the 'file' should come from File API which I've did but its always unsuccessful and im not sure what im doing wrong.
const submitForm = async (data) => {
const imageFile = data.donorPhotoFile[0] //this is the file
const imageUpload = await fetch("/api/firestorage", {
method: "POST",
body: imageFile
});
const res = await imageUpload.json()
console.log(res)
}
//in my firestorage endpoint i've done this:
const storage = getStrorage(app) //app here is an instance of my firebase initialized
const handler = async (req, res) => {
const storageRef= ref(storage)
const imageFile = req.body
try {
uploadBytes(storageRef, imageFile);
res.status(200).json({statusRes: "success"})
} catch(error) {
res.status(400).json({statusRes: "failed", errorMessage: error})
}
}
Doing that returns a storage/invalid-root-operation error code with a message of:
"Firebase Storage: The operation 'uploadBytes' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png')
So tried to make a reference to a specific file and inserted the file name as a second parameter to storageRef like this:
const storageRef = ref(storage).child(`images/${req.body.name}`)
but its still not working but now i'm getting an empty error object so I can't figure out what's wrong now. So i actually tried checking what req.body is and it's returning this:
file object in my api endpoint
I don't understand why is it like that? And what im actually looking at? What i've sent in my post request is a File object. Like this:
File object i attached to my post request
You can create a reference to a path using Modular SDK as shown below:
const storageRef= ref(storage, `images/${req.body.name}`)
The .child() method is used in older name-spaced syntax.

ReactJS testing causing a typeError: network request failed

I have been trying to simulate file-upload as a test for my react-app but that was generating the following error :
TypeError: Network request failed
at node_modules/whatwg-fetch/dist/fetch.umd.js:535:18
at Timeout.task [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:516:19)
This is my test: trying to upload a file and check if an alert is raised.
test("triggers alert when receiving a file with inadequate content", async () => {
renderComponent();
global.alert = jest.fn();
const fileContent = raw("./file.kml");
const fakeFile = new File(
[fileContent],
"file.kml",
{ type: "text/xml" }
);
const selectType = screen.getByTestId("select-type");
await fireEvent.change(selectType, { target: { value: "type" } });
const fileUploader = screen.getByTestId("file-uploader");
await fireEvent.change(fileUploader, {
target: { files: [fakeFile] },
});
await waitFor(() => {
expect(global.alert).toHaveBeenCalledWith(
"alert"
);
});
});
});
I am kind of confused, because file is received and parsed by the component and it raise the alert I need to check but still fails because of the network error.
PS: I tried to mock a fetch but still have the same problem.
Any help would be appreciated.
I have been getting the same
Network request failed: Connection refused
error while testing.
I have explored many threads but no luck.
Out of the blue starting the back end server worked for me. (Even though I used mock service worker that intercepts network calls, starting the back end server worked.)
I don't know why.
Also, I have used import fetch from 'isomorphic-fetch'; in setup-test.js instead of whatwg-fetch.
In the end try adding a timeout:3000 option to your waitFor.

Access object from server response when using yield call for a blob file

So I try to make a call to the server to get a PDF file, which works when the file exist. But when there is no file, i get a 404 response from the server. I need to access this status in the result object. The problem is when the blob tries to download and it doesnt find the file, it does not provide me with the result from server, but instead it says this:
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
If I tweak it a bit it says "Error fetching file". But I really need the status from the server response due to displaying correct info if the file does not exist or if its an server error. Due to sensitive data, I cannot copy paste the result from server in here. But it does show result: { statusCode: 404 " } in the object.
This is my code:
export function* getInvoicePDFWorkerSaga(arg) {
const {
organizationNumber, agreementId, invoiceNumber,
} = arg;
try {
const blob = yield call(invoices.getInvoicePDF, organizationNumber, agreementId, invoiceNumber);
const blobUrl = URL.createObjectURL(blob);
downloadFile(blobUrl, `invoice_${invoiceNumber}`, 'pdf');
} catch (e) {
yield put(actions.getInvoicePDFFailedAction(invoiceNumber, formatError(e)));
const retry = yield call(RetryPrompt);
if (retry) {
yield call(getInvoicePDFWorkerSaga, arg);
}
}
}
getInvoicePDF: (organizationNumber, agreementId, invoiceNumber) => (
getBlob({ url: ENDPOINTS.getInvoicePDF(organizationNumber, agreementId, invoiceNumber) })
),

Sending JSON via Postman causes an error in my Node.js service

I created schema in node.js. It worked before I included arrays.
This is my schema code:
const Item = new item_Schema({
info:{
title:{type:String, required:true},
bad_point:{type:Number, 'default':0},
Tag:{type:String, required:true}
},
review:{
Review_text:{type:Array, required:true},
Phone_list:{type:Array, required:true},
LatLng_list:{type:Array, required:true}
}
});
Item.statics.create = function(info, review){
const list = new this({
info:{
title,
bad_point,
Tag
},
review:{
Review_text,
Phone_list,
LatLng_list
}
});
return list.save();
};
This is my register code:
exports.register = (req, res) => {
const { info, review } = req.body
const create = (list) => {
return Item.create(info, review)
}
const respond = () => {
res.json({
message: 'place route registered successfully'
})
}
const onError = (error) => {
res.status(409).json({
message: error.message
})
}
RouteReviewItem.findOneBytitle(title)
.then(create)
.then(respond)
.catch(onError)
}
And this is the Postman JSON raw code:
{
"info":"{
"title":"test title",
"badPoint":"0"
"Tag":"tag1"
}",
"review":"{
"Review_text":["1번리뷰", "2번리뷰", "3번리뷰"],
"Phone_list":"["010-0000-0000", "010-1111-1111", "010-2222-2222"],
"LatLng_list":["111.1111,111.1111", "222.222,222.222","333.3333,333.3333"]
}"
}
This is the error I get in Postman:
SyntaxError: Unexpected token in JSON at position 17
at JSON.parse (<anonymous>)
at parse (C:\MainServer\node_modules\body-parser\lib\types\json.js:89:19)
at C:\MainServer\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\MainServer\node_modules\raw-body\index.js:224:16)
at done (C:\MainServer\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\MainServer\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a problem with postman? Or the node.js side?
I looked at the node.js book I was studying, but could not find any relevant information.
The code is fine, you have an issue with JSON you used for testing. For further testing and debugging, I suggest that you verify that the requests you send you the endpoint are correct by using a service like JSONLint (or any offlne tool that does the same). For the request you posted in the question, this service complains:
Error: Parse error on line 2:
{ "info": "{ "title": "test t
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Next time, before sending a request, make sure it is correct syntactically. That way you'll know that there is a problem with your code, and won't spend time debugging a non-existent issue.

Resources