How to use openWhisk forwarder combinator to forward parameters around a cloudant action - openwhisk

I have this scenario where I want to check if user's email is already been used when trying to signup and throw an error “user already exists” in that case.
here’s what my sequence looks like:
Input action -> CloudnAnt EXE QUERY-Find -> Validate email action -> CloudnAnt create User/Throw user already exists error action
my json payload looks like this :
{email: 'blahblah#domain.com', pass: "pass"}
the problem is that I have no control over the output of the cloudnant predefined actions, and by that I lose the payload after the 2nd action "CloudnAnt EXE QUERY-Find User with email action"
Is there a way to keep my input all the way through the sequence? and could the forward combinator be the solution for this issue?

I'd try /whisk.system/combinators/forwarder, which lets you pass arguments to an action and then specify arguments that get sent to the next one. Ie, I've got 5 arguments, let's pass 1 and 2 on to the next item in the sequence, and when done, pass 3, 4, 5 to the next one. I believe the output from the first item goes along as well.

The solution is very simple, just replace the cloudant action with a forward combinator which will invoke the cloudant action and forward the parameters around it.
to invoke a cloudant action you need get the full path for your action and that includes the namespace and the database name like the following:
/namespace/dbname/actionName
in my case it was /sansan/users/exec-query-find
so if you want to check whether the email exists or not in your cloudant db, and keep the original params just pass the following payload to your cloudant action
{
"data":{...},// some data you want to keep after the cloudant query
"query": {
"selector": {
"email": "email#domain.com"
}
},
"$actionName": "/sansan/users/exec-query-find",
"$forward": [// list of params you want forward
"data"
],
"$actionArgs": [ // list of params you want to feed the action
"query"
]
}
after running the sequence, the output should look like this:
{
"data": {...}, // your data
"docs": [...]// cloudant query results
}
the forward combinator is poorly documented, but you can find more details about it in Raymond Camden's blog post
look at Raymond's answer here too

Related

Powerautomate Parsing JSON Array

I've seen the JSON array questions here and I'm still a little lost, so could use some extra help.
Here's the setup:
My Flow calls a sproc on my DB and that sproc returns this JSON:
{
"ResultSets": {
"Table1": [
{
"OrderID": 9518338,
"BasketID": 9518338,
"RefID": 65178176,
"SiteConfigID": 237
}
]
},
"OutputParameters": {}
}
Then I use a PARSE JSON action to get what looks like the same result, but now I'm told it's parsed and I can call variables.
Issue is when I try to call just, say, SiteConfigID, I get "The output you selected is inside a collection and needs to be looped over to be accessed. This action cannot be inside a foreach."
After some research, I know what's going on here. Table1 is an Array, and I need to tell PowerAutomate to just grab the first record of that array so it knows it's working with just a record instead of a full array. Fair enough. So I spin up a "Return Values to Virtual Power Agents" action just to see my output. I know I'm supposed to use a 'first' expression or a 'get [0] from array expression here, but I can't seem to make them work. Below are what I've tried and the errors I get:
Tried:
first(body('Parse-Sproc')?['Table1/SiteConfigID'])
Got: InvalidTemplate. Unable to process template language expressions in action 'Return_value(s)_to_Power_Virtual_Agents' inputs at line '0' and column '0': 'The template language function 'first' expects its parameter be an array or a string. The provided value is of type 'Null'. Please see https://aka.ms/logicexpressions#first for usage details.'.
Also Tried:
body('Parse-Sproc')?['Table1/SiteconfigID']
which just returns a null valued variable
Finally I tried
outputs('Parse-Sproc')?['Table1']?['value'][0]?['SiteConfigID']
Which STILL gives me a null-valued variable. It's the worst.
In that last expression, I also switched the variable type in the return to pva action to a string instead of a number, no dice.
Also, changed 'outputs' in that expression for 'body' .. also no dice
Here is a screenie of the setup:
To be clear: the end result i'm looking for is for the system to just return "SiteConfigID" as a string or an int so that I can pipe that into a virtual agent.
I believe this is what you need as an expression ...
body('Parse-Sproc')?['ResultSets']['Table1'][0]?['SiteConfigID']
You can see I'm just traversing down to the object and through the array to get the value.
Naturally, I don't have your exact flow but if I use your JSON and load it up into Parse JSON step to get the schema, I am able to get the result. I do get a different schema to you though so will be interesting to see if it directly translates.

Trying to get a JSONPath array of all leaves on json object

New to Go. My first project is to compare a NodeJS proxy and a Go proxy for account number tokenization. I have been doing NodeJS for a few years and am very comfortable with it. My proxies will not know the format of any request or response from the target servers. But it does have configurations coming from Redis/MongoDB that is similar to JSONPath expression. These configurations can change things like the target server/path, query parameters, headers, request body and response body.
For NodeJS, I am using deepdash's paths function to get an array of all the leaves in a JSON object in JSONPath format. I am using this array and RegEx to find my matching paths that I need to process from any request or response body. So far, it looks like I will be using gjson for my JSONPath needs, but it does not have anything for the paths command I was using in deepdash.
Will I need to create a recursive function to build this JSONPath array myself, or does anyone know of a library that will produce something similar?
for example:
{
"response": {
"results": [
{
"acctNum": 1234,
"someData": "something"
},
{
"acctNum": 5678,
"someData": "something2"
}
]
}
}
I will get an array back in the format:
[
"response.results[0].acctNum",
"response.results[0].someData",
"response.results[1].acctNum",
"response.results[1].someData"
]
and I can then use my filter of response.results[*].acctNum which translates to response\.results\[.*\]\.acctNum in Regex to get my acctNum fields.
From this filtered array, I should be able to use gjson to get the actual value, process it and then set the new value (I am using lodash in NodeJS)
There are a number of JSONPath implementations in GoLang. And I cannot really give a recommendation in this respect.
However, I think all you need is this basic path: $..*
It should return in pretty much any implementation that is able to return pathes instead of values:
[
"$['response']",
"$['response']['results']",
"$['response']['results'][0]",
"$['response']['results'][1]",
"$['response']['results'][0]['acctNum']",
"$['response']['results'][0]['someData']",
"$['response']['results'][1]['acctNum']",
"$['response']['results'][1]['someData']"
]
If I understand correctly this should still work using your approach filtering using RegEx.
Go SONPath implementations:
http://github.com-PaesslerAG-jsonpath
http://github.com-bhmj-jsonslice
http://github.com-ohler55-ojg
http://github.com-oliveagle-jsonpath
http://github.com-spyzhov-ajson
http://github.com-vmware-labs-yaml-jsonpath

MS Flow: How to achieve something like `_.find()` (lodash/JS)

How can I use MS Flow to select an individual object, by value for a specified property, from an array?
Example array:
[
{
item_id: '1234'
},
{
item_id: '4567'
}
]
In the example above, I may only want to work with the first object and the rest of its available properties.
Happy to use the Workflow Definition Language and/or any of the Data Operations actions.
I solved this by using the "Data operations - Filter" action.
Ignore the error in red - it is an array.
My left-hand expression for "item_id" is:
item()?['item_id']
And then I statically enter the item ID I wish to access in the right-hand input.
DocumentNo Item will then be an array itself with only 0 or 1 elements and can be used like so:
body('DocumentNo_Item')?[0]?['label']

Variables and data files in Postman Collection Runner

I have an API get requests in Postman that uses a data file of voucher codes to look up other information about the code, such as the name of the product the code is for. When using collection runner the voucher codes are passed incorrectly and the data is returned about the product.
For some reason, I'm unable to capture the data from the response body and link this into the next request.
1st get request has this in the body section:
{
"dealId": 6490121,
"voucherCode": "J87CM9-5PV33M",
"productId": 520846,
"productTitle": "A Book",
"orderNumber": 23586548,
"paymentMethod": "Braintree",
"deliveryNotificationAvailable": true
}
I have this in the tests section to capture the values:
var jsonData = pm.response.json()
pm.environment.set("dealId", jsonData.dealId);
pm.globals.set("productId", jsonData.productId);
when posting the next request in the body:
{
"dealId":{{dealId}},
"dealVoucherProductId": {{productId}},
"voucherCode":"{{VoucherCode}}",
}
and pre-request scripts:
pm.environment.set("productId", "productId");
pm.globals.set("dealId", "dealId");
As you can see I've tried to use global and environmental variables both are not populating the next request body.
What am I missing?
This wouldn't set anything in those variables apart from the strings that you've added.
pm.environment.set("dealId", "dealId");
pm.globals.set("productId", "productId");
In order to capture the response data and set it in the variable you will need to add something like this to the first requests Tests tab:
var jsonData = pm.response.json()
pm.environment.set("dealId", jsonData.dealId);
pm.globals.set("productId", jsonData.productId);
Depending on the response schema of the first request - This should set those values as the variables.
You can just use the {{dealId}} and {{productId}} where ever you need them after that.
If you're using a environment variable, ensure that you have created an file for those values to be set.

How to print validation error outside of field constructor in Play framework 2

How can I show a validation error for a form field outside of a field constructor in Play framework 2? Here is what I tried:
#eventForm.("name").error.message
And I get this error:
value message is not a member of Option[play.api.data.FormError]
I'm confused because in the api docs it says message is a member of FormError. Also this works fine for global errors:
#eventForm.globalError.message
You can get a better grasp of it checking Form's sourcecode here
Form defines an apply method:
def apply(key: String): Field = Field(
this,
key,
constraints.get(key).getOrElse(Nil),
formats.get(key),
errors.collect { case e if e.key == key => e },
data.get(key))
That, as said in the doc, returns any field, even if it doesn't exist. And a Field has an errors member which returns a Seq[FormError]:
So, you could do something like that (for the Seq[FormError]):
eventForm("name").errors.foreach { error =>
<div>#error.message</div>
}
Or (for the Option[FormError])
eventForm("name").error.map { error =>
<div>#error.message</div>
}
Or, you could use Form errors:
def errors(key: String): Seq[FormError] = errors.filter(_.key == key)
And get all errors of a given key. Like this (for the Seq[FormError]):
eventForm.errors("name").foreach { error =>
<div>#error.message</div>
}
Or (for the Option[FormError])
eventForm.error("name").map { error =>
<div>#error.message</div>
}
If you want more details, check the source code. It's well written and well commented.
Cheers!
EDIT:
As biesior commented: to show human readable pretty messages with different languages you have to check how play works I18N out here
To be thorough you're probably going to have to deal with I18N. It's not hard at all to get it all working.
After reading the documentation you may still find yourself a bit consufed. I'll give you a little push. Add a messages file to your conf folder and you can copy its content from here. That way you'll have more control over the default messages. Now, in your view, you should be able to do something like that:
eventForm.errors("name").foreach { error =>
<div>#Messages(error.message, error.args: _*)</div>
}
For instance, if error.message were error.invalid it would show the message previously defined in the conf/messages file Invalid value. args define some arguments that your error message may handle. For instance, if you were handling an error.min, an arg could be the minimum value required. In your message you just have to follow the {n} pattern, where n is the order of your argument.
Of course, you're able to define your own messages like that:
error.futureBirthday=Are you sure you're born in the future? Oowww hay, we got ourselves a time traveler!
And in your controller you could check your form like that (just one line of code to show you the feeling of it)
"year" -> number.verifying("error.furtureBirthday", number <= 2012) // 2012 being the current year
If you want to play around with languages, just follow the documentation.
Cheers, again!
As you said yourself, message is a member of FormError, but you have an Option[FormError]. You could use
eventForm("name").error.map(_.message).getOrElse("")
That gives you the message, if there is an error, and "" if there isn't.

Resources