Unable to access Profile scope on Uber API with node-uber wrapper - uber-api

I'm trying to build a project using the Uber API and node, and was using the node-uber wrapper here: https://github.com/shernshiou/node-uber
I've been able to access the History scope with no issue, but I'm not able to get the Profile scope. Any insight into what might be wrong? Snippets below.
Thanks!
app.get('/sign-in', function (req, res) {
var url = uber.getAuthorizeUrl(['history', 'profile']);
res.redirect(url);
console.log(url);
});
app.get('/oauth/callback', function (req, res) {
var code = req.query.code
uber.authorization({ authorization_code: code },
function (err, access_token) {
req.session.uberToken = access_token
res.redirect('/my-trips');
});
});
app.get('/api/profile', function (req, res) {
uber.user.profile({access_token: req.session.uberToken}, function (err, apiResponse) {
res.send(apiResponse);
});
});

Could you please show your error message? Based on your snippet, it's hard to understand what might go wrong without making assumptions. One thing that you might check is the authorization within the callback method. More specific, this assignment:
req.session.uberToken = access_token
You're assigning the uberToken to the request, which doesn't have any effect. Modifications to the response, however, would be useful. The request property won't exist in the method scope for the GET /api/profile. Hence, accessing the profile should return a HTTP 401 (Unauthorized).

Related

Using .catch with async/await

I am wondering if I can still use .catch() within an async function to catch the error instead of using a try-catch block.
The following code is from my project using MongoDB and Express:
router.get('/communities', EnsureAuthenticated, async (req, res) =>{
//Look up the user in the db + populate the community field
const userInfo = await User_DB
.findOne({ _id:req.user._id, })
.populate('communities')
.lean()
.catch(err => {
console.log(err)
res.status(500)
.json({
msg: 'DB: Error Fetching User Info',
});
// rest of the functions that take userInfo as the input
});
When using try-catch all variables will be limited to within the scope of that try-catch block.
If I need to use the userInfo as the input for other functions down the line I'll have to put everything within that try-catch block which doesn't look clean and can be confusing. Because you don't know which function does the error belongs to if there is any.
Is my understanding correct?
I apologize for the formatting. I'm doing this on my phone.
You can also make a central error handler, you can find an example here

How to access actions in the controller

I'm a newbie trying to learn sails js, please bear with me.
As instructed in a tutorial I tried to set up my controllers and views to show a simple page just to make sure that the routing is working as expected.
So I have a PersonalController.js inside api/controllers folder. This was generated automatically from the generate cli command so I'm sure the location is correct.
Then I create a test view inside views/pages. I named it personal.ejs.
And so I modified my PersonalController to this
module.exports = {
list: function(req, res) {
return res.view('personal');
}
};
I don't know why but I'm getting an error.
I tried to just return json but I still get the same result, 404.
module.exports = {
list: function(req, res) {
return res.json({
todo: 'test'
});
}
};
I know I am missing something, just not sure what it is.

Asynchronous Request to Facebook API with Redux

I am using Redux and trying to make a call to Facebook API with their JS SDK. I've only ever used promises with Redux and so since the method FB.getLoginStatus just returns a simple JS object, I'm not sure how to ensure that the payload doesn't return undefined.
With redux-promise, you add it to the applyMiddleware(ReduxPromise)... and then it ensures nothing is returned until the promise resolves. But I don't know how to do that here.
I've also used async/await functions with React Native without an issue, but I tried using them here and for some reason the code still returns the payload, before the asynchronous request (await ...) is finished. So I tried working with redux-await, but couldn't get it to work.
export function getLoginStatus() {
var res = FB.getLoginStatus(function(res) {
console.log(res);
});
console.log("res ", res);
return {
type: GET_LOGIN_STATUS,
payload: res
}
}
Hm, things can get a little tricky as I've not used redux-promise. And I can't tell exactly what else you have tried. But this would be my first shot:
async function _getLoginStatus() {
var payload = new Promise( (resolve, fail) => {
FB.getLoginStatus((res)=>resolve(res));
});
return {
type: GET_LOGIN_STATUS,
payload: payload
}
}
// Last time I exported an async function I needed this HYMMV
export let getLoginStatus = _getLoginStatus;
And then elsewhere in the code:
import {getLoginStatus} from 'whatever.js';
var payloadResult = await getLoginStatus();

How does one access data posted within restify 1.x.x?

I'm posting data to a restify API, but cannot find any currently examples for how to access the posted data. How does this work?
I found the answer. One of the included plugins needs to be activated, restify.bodyParser. The data may then be found in either req.params (default) or req.body (mapParams: false), depending on the settings (look specifically at BodyParser section).
Example:
server.use(restify.bodyParser({ mapParams: false })); // mapped in req.body
Or:
server.use(restify.bodyParser()); // mapped in req.params
For restify 5.0.0+, use:
server.use(restify.plugins.bodyParser());
https://github.com/restify/node-restify/issues/1394#issuecomment-312728341
For older versions use:
server.use(restify.bodyParser());
After telling restify to use the bodyParser middleware the request body will be available on the request objects body property:
server.post('/article', (req, res, next) => {
console.log(req.body)
next()
})
Is very simple:
server.use(restify.bodyParser({ mapParams: false }));
You need to activate the bodyParser in restify
This code will print the request body to the console:
var restify = require('restify');
var server = restify.createServer();
// This line MUST appear before any route declaration such as the one below
server.use(restify.bodyParser());
server.post('/customer/:id', function (req, resp, next) {
console.log("The request body is " + req.body);
response.send("post received for customer " + req.params.id + ". Thanks!");
return next();
});

How to handle the response in callback functions (used by cradle in nodejs for example)

I'm using "express" and "cradle" in "nodejs". If I request my database I have to define a callback to handle the response. Unfortunately I have no access to res (response) in my callback function. What is the best practice for this problem? Here is my code.
var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
db.view('guestbook/all', function(err, doc) {
console.log(doc);
// How can I use res in this callback
// to send the response?
});
});
You can just use res inside the inner callback.
In JavaScript the inner function "inherits" the variables of the outer function. Or more precisely, the function forms a closure, which is an expression that can have free variables. The closure binds the variables from its outer scope, which can be the scope of another function or the global scope.
You may try this.
Most important (perhaps your pitfall?) keep in mind that 'db.view' will mereley register a callback closure and continue. Do not close your request (by calling 'req.end') anywhere outside this closure. If you do, quite likely the request have been closed as the db returns. Once the http response object is closed any data written to it goes void.
var cradle = require('cradle');
var db = new cradle.Connection().database('guestbook');
app.get('/guestbook', function(req, res) {
// Register callback and continue..
db.view('guestbook/all', function(err, guests) {
// console.log('The waiting had an end.. here are the results');
guests.forEach(function(guest) {
if (guest.name) {
res.write('Guest N: ' + guest.name);
}
});
// Close http response (after this no more output is possible).
res.end('That is all!')
});
console.log('Waiting for couch to return guests..');
// res.end('That is all!'); // DO NOT DO THIS!!!
});
With this snippet you really should have access to res here. You should be able to use res.render() or res.send() because the db callback is wrapped in the closure of the app.get callback function.