My pre-signup-trigger lambda fails with the InvalidLambdaResponseException. Using nodejs. The user registration works without the trigger.
I tried pretty much all solutions suggested on SO how to handle this trigger. I have tried ending the lambda with context.done(null, event) and callback(null, event). The test script works.
Worth mentioning that I have around 10 user attributes including 7 custom.
exports.handler = (event, context, callback) => {
// Check if business phone exists
event.response.autoConfirmEmail = false;
// This example uses a custom attribute "custom:domain"
if (event.request.userAttributes.hasOwnProperty("custom:business_phone")) {
if ( event.request.userAttributes["custom:business_phone"] !== null
&& event.request.userAttributes["custom:business_phone"] !== "") {
event.response.autoConfirmEmail = true;
}
}
// Return to Amazon Cognito
callback(null, event);
//context.done(null, event);
};
Test event works but user signup in browser returns InvalidLambdaResponseException. Tried one or both of the last two lines.
UPDATE: Getting same exception for Post confirm trigger. used aws doc example as is. Using runtime NodeJs 10.x. Tried 8.10 too.
To all he experts out there, please help!
I had the same problem and it turned out the error was caused by another lambda that I had in my cloudformation:
exports.handler = (event, context, callback) => {
if (event.triggerSource === "CustomMessage_ForgotPassword") {
event.response.emailSubject = "Reset your password for blah";
event.response.emailMessage = "Blah blah";
callback(null, event);
}
};
As signup sends an email, it was also executing the above lambda. But callback(null, event); was inside if statement and therefore not executed, since event.triggerSource was not "CustomMessage_ForgotPassword".
Fixing that by putting callback(null, event); outside of if statement solved the whole problem.
I'd suggest checking your other lambdas if they always execute callback(null, event) in the end, because error may be caused by a different lambda than you'd expect.
Related
I am implementing fingerprint scanning in my RN app and I found a good tutorial for that but the code there has a syntax which I have never used - yield call(), however, I googled it and couldn't find a proper explanation for it.
Here is the code:
if (isFingerPrintSupported === true) {
yield call(KeychainService.setCredentials, user_name,
JSON.stringify({ password }));
}
Is there something else I can use instead in this case? if not then how can I import this or install in order to make it work?
EDIT(example code added):
componentWillMount() {
let credentials = yield call(KeychainService.getCredentials);
if (credentials && credentials.username)) {
let isFingerPrintSupported = yield call(KeychainService.checkBiometricSupportednEnrolled);
if (isFingerPrintSupported === true) {
// show fingerprint alert on login page
// and authenticate FingerPrint when user touch the sensor
}
} else {
// else don’t show fingerprint option on login
}
}
yield can be used inside a generator function & it helps to pause and resume a function at any time asynchronously. Also Additionally it helps to return value from a generator function.
Check this document for more information.
call is redux-saga effects which help to make asynchronous calls. Check this for more information.
import { call } from 'redux-saga/effects'
function* authorize(user, password) {
try {
const response = yield call(/** Api call */, user, password)
...
} catch(error) {
...
}
}
Note
If you don't want to use yield, you can directly call you API with params using axios or fetch.
Hope this helps you. Feel free for doubts.
I need to set negation for some text content and tried the code below but as it isn't stated in the docs I expected it to fail and it sure did, so I would like to know how could I possibly achieve negation in this case.
await expect(element(by.id('myElemId'))).not.toHaveText('some text')
Unfortunately I don' think Detox has the ability to use the .not property of expect
However you could so something like this:
First create a function that returns a boolean if a specific text phrase exists. We use the fact that if a value doesn't exist it will throw and error, by wrapping it in a try/catch we can return a boolean that we can then use in our tests.
async function hasText (id, text) {
try {
await expect(element(by.id(id))).toHaveText(text);
return true;
} catch (err) {
return false;
}
}
You can then use it in the following way throwing an error if it returns true for having the text.
it('should not have some text', async () => {
await expect(element(by.id('myElemId'))).toBeVisible();
let result = await hasText('myElemId', 'some text');
// so if the text exists it will return true, as we don't want it to exist then we can throw our own error.
if (result) {
throw new Error('Should not have some text, but did.');
}
});
I know that this is not an elegant solution to the problem, and it would be much nicer if Detox gave us the APIs we needed but I suppose that this could be used in a pinch.
As of Detox version 17.11.4 you can do this
await expect(element(by.id(options.testID))).toBeNotVisible()
or
await expect(element(by.text(options.text))).toBeNotVisible()
This is the correct way to do it using the recommended setup with Jest.
I'm trying to understand an article here, and now everything is clear but one code fragment, mentioned on pre-last code block, with a total of 1 to 17 lines, and this fragment is from line 1 to 9:
app.use(function(req,res,next) {
redis.get(req.user.email, function(err, id) {
if (err) next(err);
req.emitToUser = function() {
var soc = id && io.to(id);
soc.emit.apply(soc, arguments);
}
});
});
and I think its some shortcomings in my javascript knowledge are the root cause.
My knowledge over this code fragment:
The 'apply' method will execute the 'emit' with 'soc' as 'this' value
and feeds the 'emit' method with 'arguments' (am I right here
please?)
socket.id is related to the email of socket owner, because id.to(id) is based on the fact that the socket.id is the room where every socket is joined with itself. Redis provides the key-value data structure that holds user email as key, and the value is the socket.id.
problems:
where 'arguments' is coming from?
what's the purpose of this code fragment?
Please make me clear.
There are some issues with this code, but the general idea is to define a method on the req object req.emitToUser() for every incoming request that will allow some other route handler later in the chain to use that method to emit to the user who make the request. This is a common desire to want to connect a currently connected socket.io connection to the user making the http request.
Let's look at each line here:
redis.get(req.user.email, function(err, id) {
Look up the req.user.email in the redis database to get a socket.io id associated with that email that has previously been saved in that redis database.
if (err) next(err);
If it wasn't found in redis, make this request fail with an error.
req.emitToUser = function() {
Assign a new method to the current req object so that other route handlers later in the chain can use that method.
var soc = id && io.to(id);
Look up the id value in socket.io to get the socket for that id. Technically io.to() doesn't return the socket, but it returns an object that you can call emit() on that will send to that socket.
soc.emit.apply(soc, arguments);
The role of soc.emit.apply(soc, arguments); is this:
Execute the soc.emit() method
Set the this value when executing that method to the soc object.
Set the arguments when executing that method to whatever the arguments were that were passed to req.emitToUser(x, y, z) when it was called.
Here's a more concrete example:
function fn(a, b, c) {
console.log(a, b, c);
}
fn.apply(null, [1, 2, 3]);
Using fn.apply(null, [1, 2, 3]); will be the same as:
fn(1, 2, 3);
Now, you'd likely never use .apply() in this exact way when the arguments are already known. The case for using it is when you have some arbitrary array that is passed to you (you don't know what's in it) and you want to pass those arguments along to some other function in the exact same order as they were given to you. That's what soc.emit.apply(soc, arguments); is doing. It's taking the arguments object (which is an array-like structure that represents the arguments that were passed to the parent function req.emitToUser() and passing those exact arguments on it sock.emit(). If you knew exactly how many arguments there would be, then you could hard-code that same code as this:
app.use(function(req,res,next) {
redis.get(req.user.email, function(err, id) {
if (err) next(err);
req.emitToUser = function(msg, data) {
var soc = id && io.to(id);
soc.emit(msg, data);
}
});
});
But, .apply() creates a more generic solution that will work regardless of how many arguments were passed to req.emitToUser() as it will just pass all the arguments on to soc.emit().
This line of code is a bit suspect:
var soc = id && io.to(id);
It appears to be trying to protect against there not being a proper id returned from redis earlier. But, if there's no id, then soc will not be a valid object and the following like of code:
soc.emit.apply(soc, arguments);
will throw. So, the id && io.to(id) isn't really providing the proper protection. It appears this should more likely be:
app.use(function(req,res,next) {
redis.get(req.user.email, function(err, id) {
if (err) next(err);
req.emitToUser = function() {
if (id) {
var soc = io.to(id);
soc.emit.apply(soc, arguments);
} else {
// not sure what you want here, perhaps return an error
// or throw a more meaningful exception
}
}
});
});
I had a look at the bluebird promise FAQ, in which it mentions that .then(success, fail) is an antipattern. I don't quite understand its explanation as for the try and catch.
What's wrong with the following?
some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })
It seems that the example is suggesting the following to be the correct way.
some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })
What's the difference?
What's the difference?
The .then() call will return a promise that will be rejected in case the callback throws an error. This means, when your success logger fails, the error would be passed to the following .catch() callback, but not to the fail callback that goes alongside success.
Here's a control flow diagram:
To express it in synchronous code:
// some_promise_call().then(logger.log, logger.log)
then: {
try {
var results = some_call();
} catch(e) {
logger.log(e);
break then;
} // else
logger.log(results);
}
The second log (which is like the first argument to .then()) will only be executed in the case that no exception happened. The labelled block and the break statement feel a bit odd, this is actually what python has try-except-else for (recommended reading!).
// some_promise_call().then(logger.log).catch(logger.log)
try {
var results = some_call();
logger.log(results);
} catch(e) {
logger.log(e);
}
The catch logger will also handle exceptions from the success logger call.
So much for the difference.
I don't quite understand its explanation as for the try and catch
The argument is that usually, you want to catch errors in every step of the processing and that you shouldn't use it in chains. The expectation is that you only have one final handler which handles all errors - while, when you use the "antipattern", errors in some of the then-callbacks are not handled.
However, this pattern is actually very useful: When you want to handle errors that happened in exactly this step, and you want to do something entirely different when no error happened - i.e. when the error is unrecoverable. Be aware that this is branching your control flow. Of course, this is sometimes desired.
What's wrong with the following?
some_promise_call()
.then(function(res) { logger.log(res) }, function(err) { logger.log(err) })
That you had to repeat your callback. You rather want
some_promise_call()
.catch(function(e) {
return e; // it's OK, we'll just log it
})
.done(function(res) {
logger.log(res);
});
You also might consider using .finally() for this.
The two aren't quite identical. The difference is that the first example won't catch an exception that's thrown in your success handler. So if your method should only ever return resolved promises, as is often the case, you need a trailing catch handler (or yet another then with an empty success parameter). Sure, it may be that your then handler doesn't do anything that might potentially fail, in which case using one 2-parameter then could be fine.
But I believe the point of the text you linked to is that then is mostly useful versus callbacks in its ability to chain a bunch of asynchronous steps, and when you actually do this, the 2-parameter form of then subtly doesn't behave quite as expected, for the above reason. It's particularly counterintuitive when used mid-chain.
As someone who's done a lot of complex async stuff and bumped into corners like this more than I care to admit, I really recommend avoiding this anti-pattern and going with the separate handler approach.
By looking at advantages and disadvantages of both we can make a calculated guess as to which is appropriate for the situation.
These are the two main approaches to implementing promises. Both have it's pluses and minus
Catch Approach
some_promise_call()
.then(function(res) { logger.log(res) })
.catch(function(err) { logger.log(err) })
Advantages
All errors are handled by one catch block.
Even catches any exception in the then block.
Chaining of multiple success callbacks
Disadvantages
In case of chaining it becomes difficult to show different error messages.
Success/Error Approach
some_promise_call()
.then(function success(res) { logger.log(res) },
function error(err) { logger.log(err) })
Advantages
You get fine grained error control.
You can have common error handling function for various categories of errors like db error, 500 error etc.
Disavantages
You will still need another catch if you wish to handler errors thrown by the success callback
Simple explain:
In ES2018
When the catch method is called with argument onRejected, the
following steps are taken:
Let promise be the this value.
Return ? Invoke(promise, "then", « undefined, onRejected »).
that means:
promise.then(f1).catch(f2)
equals
promise.then(f1).then(undefiend, f2)
Using .then().catch() lets you enable Promise Chaining which is required to fulfil a workflow. You may need to read some information from database then you want to pass it to an async API then you want to manipulate the response. You may want to push the response back into the database. Handling all these workflows with your concept is doable but very hard to manage. The better solution will be then().then().then().then().catch() which receives all errors in just once catch and lets you keep the maintainability of the code.
Using then() and catch() helps chain success and failure handler on the promise.catch() works on promise returned by then(). It handles,
If promise was rejected. See #3 in the picture
If error occurred in success handler of then(), between line numbers 4 to 7 below. See #2.a in the picture
(Failure callback on then() does not handle this.)
If error occurred in failure handler of then(), line number 8 below. See #3.b in the picture.
1. let promiseRef: Promise = this. aTimetakingTask (false);
2. promiseRef
3. .then(
4. (result) => {
5. /* successfully, resolved promise.
6. Work on data here */
7. },
8. (error) => console.log(error)
9. )
10. .catch( (e) => {
11. /* successfully, resolved promise.
12. Work on data here */
13. });
Note: Many times, failure handler might not be defined if catch() is
written already.
EDIT: reject() result in invoking catch() only if the error
handler in then() is not defined. Notice #3 in the picture to
the catch(). It is invoked when handler in line# 8 and 9 are not
defined.
It makes sense because promise returned by then() does not have an error if a callback is taking care of it.
Instead of words, good example. Following code (if first promise resolved):
Promise.resolve()
.then
(
() => { throw new Error('Error occurs'); },
err => console.log('This error is caught:', err)
);
is identical to:
Promise.resolve()
.catch
(
err => console.log('This error is caught:', err)
)
.then
(
() => { throw new Error('Error occurs'); }
)
But with rejected first promise, this is not identical:
Promise.reject()
.then
(
() => { throw new Error('Error occurs'); },
err => console.log('This error is caught:', err)
);
Promise.reject()
.catch
(
err => console.log('This error is caught:', err)
)
.then
(
() => { throw new Error('Error occurs'); }
)
For some reason, my code is unable to retrieve the IAsyncOperation object that is returned upon calling captureFileAsync method of the Windows.Media.Capture.CameraCaptureUI() method. The IAsyncOperation object is returned according to this documentation. In that documentation link, it states:
Return value
Type: IAsyncOperation<StorageFile>
When this operationcompletes, a StorageFile object is returned.
So here is my code:
var dialog = new Windows.Media.Capture.CameraCaptureUI();
var aspectRatio = { width: 4, height: 3 };
dialog.photoSettings.croppedAspectRatio = aspectRatio;
appSession.InAsyncMode = dialog.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).done(function (file) {
if (file) {
self.addPage(URL.createObjectURL(file));
} else {
WinJS.log && WinJS.log("No photo captured.", "sample", "status");
}
}, function (err) {
// None taken
});
When I inspect the value of appSession.InAysncMode, I see that the function returns undefined. I suspect it returns undefined because the operation is not complete (i.e. the user has not yet created the photo, and it has not been saved to disc), but I need it in order to cancel out of the camera capture mode programmatically. Does anybody know why it would return undefined instead of the documented IAsyncOperation object?
Thanks!
For reference, here's the answer I posted on the MSDN forum.
To answer your ending question, you can cancel the capture UI by canceling the promise from dialog.captureFileAsync.
Your InAsyncMode flag is undefined because you're assigning to it the return value from captureFileAsync.done() which is, by definition, undefined. It has nothing to do with the API's success.
In the docs, when you see IAsyncOperation, what you get in JavaScript is a promise that will deliver as a result to the completed handler if it succeed. You never see IAsyncOperation or related interfaces in JavaScript directly. The documentation for WinRT is written to be language-neutral, so it's important to understand how those things show up in JS (as promises). In C# you don't see it either, as you just use the await keyword. It's mostly in C++ that you actually encounter the interface.
Anyway, you I believe you want is something along the lines of the code below, where you could eliminate IsAsyncMode in favor of just checking for a non-null promise:
appSession.capturePromise = dialog.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo);
appSession.IsAsyncMode = (appSession.capturePromise != null);
//This will close the capture UI after 5 seconds--replace with whatever logic you need
setTimeout(function () { appSession.capturePromise.cancel(); }, 5000);
appSession.capturePromise.done(function (file) {
if (file) {
} else {
}
}, function (err) {
appSession.IsAsyncMode = false;
appSession.capturePromise = null;
});