Result promise being processed before it executed on Ionic 2 Facebook login - ionic-framework

I have an Ionic 2 application running the following code on an Angular 2 service:
signInWithFacebook(): firebase.Promise<any>
{
if (this.platform.is('cordova'))
{
console.log('Running on cordova...');
Facebook.login(['email', 'public_profile']).then(res =>
{
const facebookCredential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
console.log('credential value', facebookCredential);
var temp = firebase.auth().signInWithCredential(facebookCredential);
console.log('temp value: ', temp);
return temp;
});
}
else
{
return this.auth$.login({
provider: AuthProviders.Facebook,
method: AuthMethods.Popup
});
}
}
Then on my login component page I call it like this, on a login button:
pubic doFacebookLogin(): void
{
var temp = this.userDataService.signInWithFacebook()
.then(() =>
{
console.log("Passed here! [1]");
this.onSignInSuccess();
console.log("Passed here! [2]");
});
}
My console logs the following when I click the button:
Running on cordova...
main.js:46695 TypeError: Cannot read property 'then' of undefined
at LoginPage.doFacebookLogin (main.js:50920).....
credential value Lf {accessToken: "xxxxxx", provider: "facebook.com"}
temp value: I {F: 0, ka: undefined, o: I, fa: null, Ma: null…}
The flow I'm expecting is this:
call to the doFacebookLogin() method
call to the service.signInWithFacebook() method
Console logs 'Running on cordova...'
step [1] waits for the return promisse of [2]
call to Facebook.login(['email', 'public_profile'])
when the login on [4] is concluded, it calls the firebase.auth().signInWithCredential() method, which returns a promise too
Console logs 'credential value' and 'temp value'
the result promise of [5] is then returned on the service.signInWithFacebook() function
the doFacebookLogin() function finally processes the promise returned on [6] and execute onSignInSuccess()
But from the console logs we can see that it's logging 'Running on cordova', then we get an exception on the .then call of the first funcion (so the facebook login result promise was not yet processed (so the return promise doesn't exist), and after this the facebook login is processed (and now it exists, but the other function already tried to process it, generating the exception).
What am I missing with these promises?

It looks like you are just missing a return.
return Facebook.login(....).then(...);

Related

SolidJS Create Resource - Uncaught Error in Promise

I'm new to SolidJS and I'm having a weird error with resources. Here is my code:
export const authUserResource = createResource(
() => axios.get<AuthUser>('/expense-tracker/api/oauth/user').then((res) => res.data)
);
export const MyComponent = () => {
const [data] = authUserResource;
createEffect(() => console.log('HasChecked', data.loading, data.error, data()));
return (
// ...
)
}
The intent of the API call is to retrieve data on the currently authenticated user, or to return a 401 if the user is not currently authenticated. My intent is to then redirect the user based on their authentication status.
Well, the API is called and it is returning a 401 because the user is not authenticated. All of this is expected. What is not behaving is the SolidJS resource.
If the API returns a 401, I would expect the SolidJS resource data to meet these conditions:
data.loading === false
data.error instanceof Error
data() === undefined
Instead, I am finding that it is still at these conditions, based on the console.log statement in the above code example:
data.loading === true
data.error === undefined
data() === undefined
I also get an "Uncaught Error in Promise" error message in the browser JS console.
I'm hoping to figure out what I am doing wrong here to make the resource correctly handle the error so that I can gracefully handle this in my application.

While testing error responses, the test fails with the expected error (React/Jest/ReactQuery/Axios/MSW)

I am trying to test error states of the following MSW rest endpoint:
import { rest } from 'msw'
export const exceptionHandlers = [
rest.post(config.accountApiUrl + '/login', (req, res, ctx) => {
return res(
ctx.status(500),
ctx.json({ data: { message: 'Mock Error Message' } })
)
})
]
This endpoint is called in a custom hook return function thats using React Query's mutateAsync:
const { mutateAsync } = useMutation(AuthApi.login)
const handleLogin = async (props): Promise<void> => {
await mutateAsync(props, {
onSuccess: async () => {
// this block tests fine
}
onError: async () => {
console.log('!!!')
// it reaches this block, '!!!' is logged to the console,
// but the test still fails with `Request failed with status code 500`
}
})
}
return handleLogin
In a test file:
it('handles network errors', async () => {
mswServer.use(...exceptionHandlers)
const user = userEvent.setup()
const screen = render(<LoginForm />)
const submitButton = screen.getByTestId('Login.Submit')
// Complete form
await user.click(submitButton)
})
It doesnt matter what comes after that, the test always fails with
Request failed with status code 500
at createError (node_modules/axios/lib/core/createError.js:16:15)
at settle (node_modules/axios/lib/core/settle.js:17:12)
at XMLHttpRequestOverride.onloadend (node_modules/axios/lib/adapters/xhr.js:54:7)
at XMLHttpRequestOverride.trigger (node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:176:17)
at node_modules/#mswjs/interceptors/src/interceptors/XMLHttpRequest/XMLHttpRequestOverride.ts:354:16
But its supposed to fail with status 500. That's the whole point. If I change the handler to return another error, ie ctx.status(404), then the test just fails with that error code.
I've tried wrapping the assertion in a try/catch block but the same thing results. I see examples online of people doing (apparently) exactly this and it works fine, so I'm quite confused what's causing this. All other tests that check success states work as expected.
i've had the same problem.
As far as i could understand, the problem is that in test environment there is no handler for the rejected promise.
https://github.com/TanStack/query/issues/4109

Service Worker Fails on caches.open()

I'm trying to get a basic service worker up and running.
The problem I have is that when I run "caches.open()", the browser throws a
sw.js:1 Uncaught (in promise) DOMException: Unexpected internal error
Commenting out the caches.open removes the exception.
How can I get more information from the browser to tell me what's wrong?
Here's the service worker and registration code.
var CACHE_NAME = 'pwacache-v1';
var urlsToCache = [
'/',
'main.css'
];
self.addEventListener('install', function (event) {
// Perform install steps
console.log('install');
try {
event.waitUntil(getFiles());
} catch (ex) {
console.log(ex);
}
});
function getFiles() {
console.log('opening: ' + CACHE_NAME );
/*
triggers Uncaught (in promise) DOMException: Unexpected internal error
*/
caches.open(CACHE_NAME).then(function (cache) {
return Promise.all(
urlsToCache.map(function (url) {
console.log(url);
return cache.add(url).catch(function (reason) {
console.log([url + "failed: " + String(reason)]);
});
}) // end of map
);
});
console.log('waiting 3...')
}
And the registration code
// https://developers.google.com/web/fundamentals/primers/service-workers/registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('sw.js');
});
}
I do see the sw.js registered in Chrome's 'Application' tab.
You need to return a promise from getFiles() in order for the event.waitUntil() to actually wait for the async work. So I recommend returning the promise returned by your promise chain started with caches.open().
Without this its possible the service worker is being terminated before the async work can complete.

sails helpers and machine spec

I upgrade sails to the #^1.0.0 version and while I'm developing an API, I wanted to use a Service but the Sails document advice to use Helper now. And I don't realy use to work with the new way to discripe helper, build script or actions.
And all the try I have mad wasn't successful.
In the following exemple..
Here is my controller call:
var ob = await ails.helpers.testy('sayHello');
res.json({ob:ob});
helper
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: async function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
I'm getting this error
error: A hook (`helpers`) failed to load!
error:
error: Attempted to `require('*-serv\api\helpers\testy.js')`, but an error occurred:
--
D:\*-serv\api\helpers\testy.js:28
fn: async function (inputs, exits) {
^^^^^^^^
SyntaxError: Unexpected token function.......
and if I remove the "async" and the "await" form the Controller, the ob object return null and I'm having this error
WARNING: A function that was initially called over 15 seconds
ago has still not actually been executed. Any chance the
source code is missing an "await"?
To assist you in hunting this down, here is a stack trace:
```
at Object.signup [as auth/signup] (D:\*-serv\api\controllers\AuthController.js:106:26)
The first guy from the comments is right.
After removing async from fn: async function (inputs, exists) {}; you need to setup sync: true which is false by default. It is described at helpers doc page at Synchronous helpers section.
So your code should look like this
module.exports = {
friendlyName: 'Testy',
description: 'Testy something.',
sync: true, // Here is essential part
inputs: {
bla: {
type: 'string'
}
},
exits: {
success: {
}
},
fn: function (inputs, exits) {
console.log({blabla:inputs.bla})
if(!inputs.bla) return exits.error(new Error('text not found'));
var h = "Hello "+ inputs.bla;
// All done.
return exits.success(h);
}
};
From the another side, you have a problem with async/await. The top most reason for this are
Not supported Node.js version - check that you current version support it
If you use sails-hook-babel or another Babel related solution, you may miss required plugin for async/await processing

Auth0 custom database mongodb, signup script is returning SandboxTimeoutError

I'm trying to use my own mongo database which is created in mlab in auth0 for user management. Here is the template they provided.
function create (user, callback) {
mongo('mongodb://user:pass#mymongoserver.com/my-db', function (db) {
var users = db.collection('users');
users.findOne({ email: user.email }, function (err, withSameMail) {
if (err) return callback(err);
if (withSameMail) return callback(new Error('the user already exists'));
bcrypt.hashSync(user.password, 10, function (err, hash) {
if (err) { return callback(err); }
user.password = hash;
users.insert(user, function (err, inserted) {
if (err) return callback(err);
callback(null);
});
});
});
});
}
After changing connection URI, I tried to "create" a user by providing email and password with the script. I see the following error:
[SandboxTimeoutError] Script execution did not complete within 20 seconds. Are you calling the callback function?
I followed the Debug Script they provided. Here is the log:
$ wt logs -p "myservice-eu-logs"
[12:35:27.137Z] INFO wt: connected to streaming logs (container=myservice)
[12:35:29.993Z] INFO wt: new webtask request 1478435731301.992259
[12:35:30.047Z] INFO wt: { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
[12:35:30.047Z] INFO wt: js-bson: Failed to load c++ bson extension, using pure JS version
[12:36:05.080Z] INFO wt: finished webtask request 1478435731301.992259 with HTTP 500 in 35096ms
Any suggestions?
Actually, bcrypt.hashSync is a synchronous method, so the callback function is never called and the script times out.
Either use:
var hashedPwd = bcrypt.hashSync(user.password);
or
bcrypt.hash(user.password,10,function(....);