How to set up a Binance WebSocket Connection with Vapor? - swift

I tried setup Binance websocket like this, what do I miss?
app.get("hello") { req -> EventLoopFuture<String> in
return WebSocket.connect(to: "wss://stream.binance.com:9443", headers: HTTPHeaders([("binance-api-key", "api-key"), ("binance-api-secret", "api-secret"), ("signature", "dcad576d5d0d9e25ee3fe427b0a50cdf9adec8ec528be05c9f1f7c684ee165f0")]), configuration: .init(), on: req.eventLoop, onUpgrade: { ws in
return
}).map({ _ in
return "done"
})
}
I reaise an error:
{
"error": true,
"reason": "invalidResponseStatus(HTTPResponseHead { version: HTTP/1.1, status: badRequest, headers: [(\"Date\", \"Sun, 12 Dec 2021 17:41:54 GMT\"), (\"Content-Type\", \"text/plain\"), (\"Content-Length\", \"20\"), (\"Connection\", \"keep-alive\")] })"
}

Related

How do I download PDF files with CapacitorHttp

Do to issues with the server setting being controlled by another party who will not add (CORS) I am forced to use CapacitorHttp to access the file Url.
Here is what I have so far
ts
async downloadPDF( FullName: any, URL: any) {
const options = {
url: URL,
headers: {
'x-authorization-token': 'XXXXXXXXX',
'access-control-allow-origin': 'https://XXXXXXXXXXXX/',
'access-control-allow-methods': 'GET,POST,OPTIONS',
'access-control-allow-headers': 'Content-Type, X-Authorization-Token, Origin',
},
params: { }, // can I add a version of responseType: 'blob' here
};
const response: HttpResponse = await CapacitorHttp.get(options);
// Type 'HttpResponse' is missing the following properties from type 'Blob': size, type, arrayBuffer, slice, and 2 more.ts(2740)
write_blob({
directory: Directory.Documents,
path: `${FILE_DIR}/${FullName}`,
blob: response
});
}
and the response is
response {"headers":{
"Cache-Control":"no-cache,private",
"Server":"nginx",
"Etag":"\"632cc89b-1abb7\"","Last-Modified":"Thu,22 Sep 2022 20:42:03 GMT",
"Content-Disposition":"inline; filename=\"sample upload.pdf\"",
"Accept-Ranges":"bytes",
"Content-Length":"109495",
"Date":"Thu, 24 Nov 2022 16:15:26 GMT",
"Content-Type":"application/pdf"},
"url":"https://XXXXXXXXXX",
"status":200
}
Is there a way I can add a version responseType: 'blob' to CapacitorHttp
Turns out CapacitorHttp causes a lot of issues and for myself it even interfered with #angular/common/http and caused it not to work. I instead used
https://github.com/capacitor-community/http
import { Http, HttpDownloadFileResult } from '#capacitor-community/http';
import { Filesystem, Directory } from '#capacitor/filesystem';
async downloadFile(name: any, URL: any) {
const options = { url: URL, filePath: `${FILE_DIR}/${name}`, fileDirectory: Directory.Documents, method: 'GET', };
const response: HttpDownloadFileResult = await Http.downloadFile(options);
}
This downloaded and saved files on iOS and Android with no CORS issues

404 Not Found on Github API using github.rest.git.createRef

I use the following code inside a Github Action workflow file:
await github.rest.git.createRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: 'refs/heads/' + '${{ github.event.inputs.combineBranchName }}',
sha: baseBranchSHA
});
The code results into a 404 :
RequestError [HttpError]: Not Found
at /home/runner/work/_actions/actions/github-script/v6/dist/index.js:6173:21
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async eval (eval at callAsyncFunction (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:13340:16), <anonymous>:71:3)
at async main (/home/runner/work/_actions/actions/github-script/v6/dist/index.js:13436:20) {
status: 404,
response: {
url: 'https://api.github.com/repos/myusername/myrepo/git/refs',
status: 404,
headers: {
...
},
data: {
message: 'Not Found',
documentation_url: 'https://docs.github.com/rest/reference/git#create-a-reference'
}
},
request: {
method: 'POST',
url: 'https://api.github.com/repos/myusername/myrepo/git/refs',
headers: {
accept: 'application/vnd.github.-preview+json',
'user-agent': 'actions/github-script octokit-core.js/3.6.0 Node.js/16.13.0 (linux; x64)',
authorization: 'token [REDACTED]',
'content-type': 'application/json; charset=utf-8'
},
body: '{"ref":"refs/heads/combined-prs-branch","sha":"a3167bb784fa5d045bbad57545a7a96c5d89be4f"}',
request: { agent: [Agent], hook: [Function: bound bound register] }
}
}
I'm using a PAT that has access to public repo.
I went from 403 error with GITHUB_TOKEN to 404 with PAT_TOKEN.
So I guess I solved the permission issue but why is it 404 now ?
I can access the URL https://api.github.com/repos/myusername/myrepo/git/refs in a browser.

get pdf from axios utility in node.js

I have created a utility function which is supposed to be common for all the api requests in node.js express app.
function axiosCall(method, endpoint, body) {
let requestConfig = {
url: encodeURI(`${endpoint.host}:${endpoint.port}${endpoint.path}`),
method: method, //can be POST, GET, etc
proxy: false,
data: body,
headers: {
"x-access-token": token,
"X-Correlation-ID": correlationId,
"Content-Type": "application/json"
},
}
axios.request(requestConfig).then(response => {
return response.data;
}).catch((errorRes) => {
throw {
error: errorRes.message, status: errorRes?.response?.status || 500,
responseContent: errorRes?.response?.data || "Server Error"
};
})
}
it works fine for JSON responses, but does not give proper result for files, such as pdf.
the response which i got for a pdf file was like
{
"status": 200,
"statusText": "OK",
"headers": {
"server": "nginx/1.16.1",
"date": "Fri, 02 Sep 2022 07:39:44 GMT",
"content-type": "application/pdf",
"content-length": "47658",
"connection": "close",
},
"config": {...},
"request": {...},
"data": "%PDF-1.4\r\n%����\r\n1 0 obj\r\n<<\r\n/Type /Catalog\r\n/Pages 2 0 R\r\n/AcroForm 3 0 R\r\n>>\r\nendobj\r\n4 0 obj\r\n<<\r\n/�����M��0\u0010��B�C������\u0016�#?���`��\u0003�N���\u0012���~�L��\u001e| O2�y3���;�fP�o�\u0013\u000e�Ҹ�c��}����E�VuS\r�W��Vv�h�>=�\u0001oGwi�j�⯰�\u000f����=�,��5��]��g{�ŧ{���\rݠ\u0012\u0000U�%��Vv��\rUL5�c\u001d���1\u000f\u0015�'�\u001f\u001d*M��jk컲B_�+N�U�$\u0019\u0004�-L\"t��\u0001�s���Z��\t�*MA����\u0005a���h�4O�\u0006�)H�9\bm�j\u0001BkX-Ah-+��i�wm#h\u0017�� �KV{\u0010�\r�\u0003\b햔I#hw��a�嶍\u0006�=��#Xp^��c\u0016ܣ1 ,4+N�Xp^!#a���X�\u0005�c8Ob�Il薑:IC�᭟oJ�\u001e�3����އy�\t�A\u001aG�q(C޵�X��7��\u0000�t��\r\nendstream\r\nendobj\r\n26 0 obj\r\n<<\r\n/Type /Font\r\n/Subtype /CIDFontType2\r\n/BaseFont /GBMOJY+SymbolMT\r\n/CIDToGIDMap /Identity\r\n/DW 1000\r\n/FontDescriptor 31 0 R\r\n/CIDSystemInfo <<\r\n/Registry (Adobe)\r\n/Ordering (Identity)\r\n/Supplement 0\r\n>>\r\n\r\n/W [120 [459]]\r\n>>\r\nendobj\r\n27 0 obj\r\n<<\r\n/Filter /FlateDecode\r\n/Length 225\r\n>>\r\nstream\r\nx^m�ϊ�0\u0010��\u001c� �^�P\n�\"����\u0000i2-��$L�C�~�T\u0014\u0016\u000f\u0019\u0018~�\r_F��sE6��a�k\f�Z2��\u001bY#4�Y\u0012�\u001d\u0018�\u0003,]��W>\u00133]OC����AQ���t\b<��ø\u0006��\r17~��0CM`\u001f��+��W�la��B��6\u000f��6l�$�֥�n��J�K���S[~ݤ�\u0003�5�]}ր����TV���ճG��Di���xQa� ?�K��\r�����ސmT�}q��Ԙ��\u0019�֕�\u0018c�\u0001�\u001a|/}!��qfJў<y��\u0007c��y\t\u001c\b ks]v]Fmz弦o\u0019����u�v_�|�[_F>�G�w�m:n��.�m$�ZҨ�F-i�\u0014〯�o\u001c�\u00120fJ\u0012`��Oz��{rP�v\u0011\u0004�}�����\u001d�\u0016�L\\�\u000b�\u001d�n�C]�I�����MZ�~۷��Iu��\u0014�6o�?�����W��ꡦ#?ZXG��wL�\u0007���G\t���3�Y���DFl�����R� 34\r\n>>\r\n\r\nstartxref\r\n46886\r\n%%EOF\r\n"
}
I am unable to convert this response.data to pdf file.
Then i read about setting responseType: "arraybuffer", which gave the buffer[] and I can use it in code to generate the file. but on setting the responseType, the error was also of buffer type instead of json. which again required further processing to convert it to json format.
so, is there a way to get pdf file from axios, by converting the response.data, which I received with default responseType.
or can we set responseType dynamically after getting response from the server, as i get the content-type in headers. so as to make a utility function which can work with all kinds of responses.
As I didn't get a proper resolution i handled it manually by passing a flag to the axios utility function.
const customObjectify = (data) => {
try {
if(typeof data === "string"){
JSON.parse(data);
}
return data;
} catch (error) {
return data;
}
}
main block is below
//adding a default value false to parameter, so i don't need to change at all function calls.
function axiosCall(method, endpoint, body, isFileInResponse= false) {
let requestConfig = {
url: encodeURI(`${endpoint.host}:${endpoint.port}${endpoint.path}`),
method: method, //can be POST, GET, etc
proxy: false,
data: body,
headers: {
"x-access-token": token,
"X-Correlation-ID": correlationId,
"Content-Type": "application/json"
},
}
if(isFileInResponse){
requestConfig.responseType = "arraybuffer";
}
axios.request(requestConfig).then(response => {
return response.data;
}).catch((errorRes) => {
try {
let responseContent;
if(isFileInResponse) {
// arraybuffer error needs to be converted to json
responseContent = customObjectify(errorRes.response.data.toString());
} else {
responseContent = errorRes.response.data;
}
throw ({ error: errorRes.message, status: errorRes?.response?.status || 500, responseContent});
} catch (error) {
throw ({ error: errorRes.message, status: errorRes?.response?.status || 500, responseContent: "Server Error" });
}
throw {
error: errorRes.message, status: errorRes?.response?.status || 500,
responseContent: errorRes?.response?.data || "Server Error"
};
})
}
As mentioned in this question (https://stackoverflow.com/a/53230807/19179818) you could put code in your .then() to create an anchor tag on your page and click it automatically to download the file, and delete the tag afterwards. (posted as awnser instead of comment because of not enough reputation)

Remove X-Socket-Id from axios get request

I get a CORS error and most likely is from X-Socket-Id. I tried to remove X-Socket-Id from Request Headers, but is not working..
.... has been blocked by CORS policy: Request header field x-socket-id is not allowed by Access-Control-Allow-Headers in preflight response.
.get(this.$URL + "/search/", {
params: {
q: this.search,
},
headers: {
Authorization: "Basic " + btoa(this.$KEY+ ":"),
},
transformRequest: (data, headers) => {
delete headers.common["X-Socket-Id"];
return data;
},
})
I found out a solution. Create axios with default settings, and for my specific case I had to remove X-Requested-With.
X-Sockets-Id, was already removed in my request.
var instance = axios.create();
delete instance.defaults.headers.common["X-Requested-With"];
instance
.get(this.$URL+ "/search/", {
params: {
q: this.search_for_company,
},
headers: {
Authorization: "Basic " + btoa(this.$KEY+ ":"),
},
})

Directus HTTP PUT Method Not Allowed

Hey I'm using Directus with Ionic 3 for browser and I got a problem with HTTP PUT.
The error:
error: {code: 6, message: "Method Not Allowed"}
proto: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null,
lazyInit: ƒ}
message: "Http failure response for
http://example.com/backend/api/public/_/users?single=1&access_token=myToken&filter[id]=50:
405 Method Not Allowed"
name: "HttpErrorResponse"
ok: false
status: 405
statusText: "Method Not Allowed"
url:
"http://example.com/backend/api/public/_/users?single=1&access_token=myToken&filter[id]=50"
This my code:
updatePwd(user:any, userId: any){
return this.api.put('users?single=1&access_token=myToken&filter[id]='+userId,user).map((res: any) => {
return res;
});
}
The POST and GET work good like that
newUser(user:any){
return this.api.post('users?access_token=myToken',user).map((res: any) => {
return res;
});
}
getUser(email:any){
return this.api.get('users?single=1&access_token=myToken&filter[email]='+email).map((res: any) => {
return res;
});
}
I'm new user of Directus and I don't know much about it. So what the problem here? I must config something or what?
Thanks in advance :)
Edit:
I tried with PATCH and It works fine ^^
updatePwd(userId: any, user:any){
return this.api.patch('users/'+userId+'?&access_token=myToken',user).map((res: any) => {
return res;
});
}
Directus uses PATCH instead of PUT for updating rows: https://docs.directus.io/api/reference.html#update-user