Error while using Request-Promise with Falcor - falcor

I am trying to do a Falcor GET call to an external api using Request-Promise (rp) package. I am getting the response in "res" (line no.8) but I am not able to return it to the Falcor model path (line no.13). It gives a "Uncaught (in promise)" error.
Also, I tried to put the return statement (line 13) inside the then block (i.e.) after line 8. Then it give "GET http://localhost/getBusinessTypes... 500 (Internal Server Error)" error.
1) router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
2) return new falcorRouter([
3) {
4) route: "businessTypes.all",
5) get: function() {
6) rp('http://localhost:8000/service?method=getBusinessTypes')
7) .then(function (res) {
8) console.log("Response from external Api: " + res);
9) })
10) .catch(function (err) {
11) console.log(err);
12) });
13) return {path: ["businessTypes", "all"], value: $atom(res)};
14) }
15) }
16) ]);
17) }));
Let me know what is missing here.

Try returning the promise from the rp() call:
router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
return new falcorRouter([{
route: "businessTypes.all",
get: function() {
return rp('http://localhost:8000/service?method=getBusinessTypes')
.then(function (res) {
console.log("Response from external Api: " + res)
return {
path: ["businessTypes", "all"],
value: $atom(res)
}
})
.catch(function (err) {
console.log(err)
// Handle error
})
}
}])
}))
You can use async/await like this:
router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
return new falcorRouter([{
route: "businessTypes.all",
get: async function() {
try {
let result = await rp('http://localhost:8000/service?method=getBusinessTypes')
console.log("Response from external Api: " + result)
return {
path: ["businessTypes", "all"],
value: $atom(result)
}
}
catch(err) {
console.log(err)
// Handle error
}
})
}])
}))

Related

Send Blob over POST http request with string values

Hi I am trying to do a http POST request to send some blob data. But I also need to send some string values with it for authentication (jwt).
let options = {uname: user.uname, authKey: user.authKey, video: qde.debrief.blob}
let xhr = await xhrRequest(`${serverIp}/api/file`, "POST", options, 'none');
prom.push(xhr);
And the xhrRequest method is
//xhr function with url input and isValid and data output
function xhrRequest(url, type, body, header) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve({ error: false, body: JSON.parse(xhr.response) });
} else if (xhr.readyState === 4 && xhr.status !== 200) {
resolve({ error: true, body: JSON.parse(xhr.response) });
}
}
xhr.timeout = 5000;
xhr.ontimeout = () => {
resolve({ error: true, body: "Error Connecting to server" });
}
xhr.onerror = function () {
resolve({ error: true, body: "Error Connecting to server" });
}
xhr.open(type, url, true);
if (type == "POST") {
if(!header){
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.send(body)
} else {
xhr.send();
}
})
}

AWS Lambda HTTPS post to Paypal IPN error

I have been trying to implement Paypal's IPN using AWS Api Gateway to get an IPN handler url. the api is integrated with a Lambda function as the "receiver".
I have tested the api gateway url using Paypal's IPN simulator.It works for the first step and I get this message "IPN was sent and the handshake was verified".
My problem is now with the next step,where I have to send the recived message back to Paypal using HTTPS post. I have tried a number of times and keep getting this error:
{
"code": "ECONNREFUSED",
"errno": "ECONNREFUSED",
"syscall": "connect",
"address": "127.0.0.1",
"port": 443
}
I really would appreciate some help in getting this to work.
I'm using node.js 8.10.Here's my Lambda function:
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
// Return 200 to caller
console.log('sending 200 back to paypal');
callback(null, {
statusCode: '200'
});
// Read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
console.log('modifying return body...');
var body = 'cmd=_notify-validate&' + event.body;
callHttps(body, context);};
function callHttps(body, context) {
console.log('in callHttp()....');
var https = require('https');
var options = {
url: 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr',
method: 'POST',
headers: {
"user-agent": "Nodejs-IPN-VerificationScript"
},
body: body
};
const req = https.request(options, (res) => {
res.on('data', (chunk) => {
// code to execute
console.log("on data - can execute code here....");
});
res.on('end', () => {
// code to execute
console.log("on end - can execute code here....");
});
});
req.on('error', (e) => {
console.log("Error has occured: ", JSON.stringify(e, null, 2));
});
req.end();}
managed to sort it out.i was using url instead of breaking it down to host and path.here's the full code that worked for me:
exports.handler = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
// Return 200 to caller
console.log('sending 200 back to paypal');
callback(null, {
statusCode: '200'
});
callHttps(event.body, context);};
function callHttps(body, context) {
console.log('in callHttp()....');
// Read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
console.log('modifying return body...');
var bodyModified = 'cmd=_notify-validate&' + body;
var https = require('https');
var options = {
host: "ipnpb.sandbox.paypal.com",
path: "/cgi-bin/webscr",
method: 'POST',
headers: {
'user-agent': 'Nodejs-IPN-VerificationScript',
'Content-Length': bodyModified.length,
}
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
var result = '';
res.on('data', (d) => {
// get the result here
result += d;
});
res.on('end', (end) => {
// check the result
if (result === 'VERIFIED') {
// process the message
// split the message
var res = body.split("&");
// create an object
var paypalMessageObject = new Object();
// loop through split array
res.forEach(element => {
// split element
var temp = (element.toString()).split("=");
// add to the object
paypalMessageObject[temp[0]] = temp[1];
});
console.log('paypalMessageObject: ' + JSON.stringify(paypalMessageObject, null, 2));
var checkItems = {
payment_status: paypalMessageObject.payment_status,
mc_gross: paypalMessageObject.mc_gross,
mc_currency: paypalMessageObject.mc_currency,
txn_id: paypalMessageObject.txn_id,
receiver_email: paypalMessageObject.receiver_email,
item_number: paypalMessageObject.item_number,
item_name: paypalMessageObject.item_name
};
console.log('checkItems: ', JSON.stringify(checkItems, null, 2));
}
else { console.log('not verified, now what?'); }
});
});
req.on('error', (e) => {
console.log("Error has occured: ", JSON.stringify(e, null, 2));
});
req.write(bodyModified);
req.end();}

Possible Unhandled Promise Rejection (id: 0): TypeError:

I'm using react native code for my app I'm getting this error,
Possible Unhandled Promise Rejection (id: 0):
TypeError: _this.props.get_categories().then is not a function. (In '_this.props.get_categories().then(function (res) {
console.log('attachment_res====>' + JSON.stringify(res));
})', '_this.props.get_categories().then' is undefined)
I coded the below code in actions.js
export function get_categories() {
return dispatch => AppAPI.categories.get('?filter={"where":{"is_active":1},"order":"is_featured desc","include":{"0":"attachment","service":{"where":{"is_active":1},"0":"attachment"}}}')
.then((responseData) => {
console.log('UserActions get categories res' + JSON.stringify(responseData) );
return responseData;
}).catch((err) => {
console.log('UserActions get categories err' + JSON.stringify(err) );
const error = AppAPI.handleError(err);
return err;
});
}
Called this code in scene
get_attachments = async() => {
await this.props.get_categories()
.then((res) => {
console.log('attachment_res====>' + JSON.stringify(res));
}).catch((error) => {
console.log('attachment_error====> ' + JSON.stringify(error));
});
}
Can anyone help me with this error???? Please!!!!!

Service Worker w offline.html Backup Page

I can't get the offline.html page to display. I keep getting the The FetchEvent for "https://my-domain.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".
Here's the snippet of my service-worker.js which should return the offline.html when the network is unavailable.
self.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
if(event.request.url.includes("my-domain.com")){
console.log(event.request);
event.respondWith(
caches.match(event.request).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
let responseClone = response.clone();
caches.open(CACHE_NAME).then(function(cache) {
cache.put(event.request, responseClone);
});
return response;
});
}).catch(function() {
return caches.match("/offline.html");
})
);
}
}
});
Below is the console.log of my network request (page refresh when offline)
Request {method: "GET", url: "https://my-domain.com", headers: Headers, destination: "unknown", referrer: "", …}
bodyUsed:false
cache:"no-cache"
credentials:"include"
destination:"unknown"
headers:Headers {}
integrity:""
keepalive:false
method:"GET"
mode:"navigate"
redirect:"manual"
referrer:""
referrerPolicy:"no-referrer-when-downgrade"
signal:AbortSignal {aborted: false, onabort: null}
url:"https://my-domain.com"
__proto__:Request
I got this working / found the fix. It was related to a redirected response security issue in the browser. From the Chromium Bugs Blog, Response.redirected and a new security restriction.
Solution: To avoid this failure, you have 2 options.
You can either change the install event handler to store the response generated from res.body:
self.oninstall = evt => {
evt.waitUntil(
caches.open('cache_name')
.then(cache => {
return fetch('/')
.then(response => cache.put('/', new Response(response.body));
}));
};
Or change both handlers to store the non-redirected response by setting redirect mode to ‘manual’:
self.oninstall = function (evt) {
evt.waitUntil(caches.open('cache_name').then(function (cache) {
return Promise.all(['/', '/index.html'].map(function (url) {
return fetch(new Request(url, { redirect: 'manual' })).then(function (res) {
return cache.put(url, res);
});
}));
}));
};
self.onfetch = function (evt) {
var url = new URL(evt.request.url);
if (url.pathname != '/' && url.pathname != '/index.html') return;
evt.respondWith(caches.match(evt.request, { cacheName: 'cache_name' }));
};

sails.js req.file.upload with bluebird promise

I'm using sails.js as my backend with bluebird promise, I tried to upload file using req.file.upload, the callback way works just fine and the file gets uploaded:
req.file('file').upload({
maxBytes: 2000000,
dirname: 'uploadFolder'
}, function (err, files) {
if (err) {
return res.serverError(err);
}
return res.ok();
}
But the promise way does not:
var Promise = require('bluebird');
var fileUploader = Promise.promisify(req.file('file').upload);
fileUploader({
maxBytes: 2000000,
dirname: currentUploadFolder
}).then(function(files) {
console.log(files);
return Promise.resolve(files);
}).catch(function(err) {
console.log(err);
return Promise.reject(err);
});
File doesn't get uploaded and the console keeps complaining:
data: app.js:1800 - [TypeError: Cannot read property 'length' of undefined]
Any thoughts please?
This case is unique and you can't use promisify here. You need to create new Promise and return it.
return new Promise(function(resolve, reject) {
req.file('file').upload({
maxBytes: 2000000,
dirname: 'uploadFolder'
}, function (error, files) {
return error ? reject(error) : resolve(files);
}
});
You can move it to helper\services\whatever and got something like this
// api/services/UploadService.js
module.exports = {
uploadFile: function(req) {
return new Promise(function(resolve, reject) {
req.file('file').upload({
maxBytes: 2000000,
dirname: 'uploadFolder'
}, function (error, files) {
return error ? reject(error) : resolve(files);
}
});
}
};
// api/controllers/AnyController.js
module.exports = {
upload: function(req, res) {
UploadService
.uploadFile(req)
.then(res.ok)
.catch(res.negotiate);
}
};

Resources