Access to a JSON Value in Angular 7 - node.js

Hello I'm trying to access to an especific key from a JSON. I'm using node.js and angular 7
The JSON I got is stringfy and it comes from an API.
This is the JSON I got
"search": {
"entry": [
{
"dn": "uid=080030781,c=mx,ou=s,o=i.com",
"attribute": [
{ "name": "mail", "value": ["CAMILA.CAMPOS.TELLEZ#mail.com", "MX08#mail.com"] }]
}
],
"return": {
"code": 0,
"message": "Success",
"count": 1
}
}
}
I need to access to the key "value", because I need to get the value "camila.campos.tellez#mail.com".
I get the JSON from an API declarated in a node.js file called app.js, then I catch the response from it using this service.ts file
getApproverMail(name) {
console.log('entered to rootservice');
return this.http.get(this.baseUrl + '/costing/operations?name=' + name);
}
Finally I can access to this through a component.ts fil with this code
findApproverMail() {
this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
this.email = res;
console.log('Test: ' + res);
});
}
And the browser console prints the JSON I have show you. But how can I access only to the mail's value?
P.D I need only the mail because after I got it the web site needs to send an email to that direction

JSON stands for JavaScript Object Notation. Any valid JSON is an object in JavaScript (and TypeScript). You can use dot notation to navigate into the object:
findApproverMail() {
this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
this.email = res.search.entry[0].attribute[0].value[0];
console.log('Test: ' + res);
});
}
I would recommend defining an interface in the shape of what you expect from the service. It's cleaner than just indexing around an any typed object.
Also note that I hard code 0 indexes because that answers your question. You might consider a more dynamic / flexible way to get the address or elements you need.

Related

(NodeJS) WordPress API, updating Events Calendar event (tribe event) removes featured image from post

I'm using the Wordpress API to update tribe events. The updates are successfully sent (and the change is made) but as a side-effect, any time I do it, the featured image is removed from the post...
wpapi package setup:
Because The Events Calendar has it's own routes that aren't built-in by default in the wpapi package, I use the wp.registerRoute function to set that up. I don't think there's a problem with the way I set that up because otherwise it works.
var WPAPI = require( 'wpapi' );
var wp = new WPAPI({
endpoint: 'https://www.example.com/wp-json',
username: 'username',
password: 'mypassword'
});
wp.tribeevent = wp.registerRoute('tribe/events/v1', '/events/(?P<id>)');
example update:
function showEvent (post_id) {
let data = { "hide_from_listings" : false }
wp.tribeevent().id(post_id).update(data)
}
Haven't been able to find anyone with this issue online, so I'm posting here after exhausting myself trying to get it to work without removing the image... Am I doing this wrong? Is this just a bug? Any suggested workarounds?
I've also tried adding the existing image info into the update data sent, but I get this response when doing so:
{
"error": {
"code": "rest_invalid_param",
"message": "Invalid parameter(s): image",
"data": {
"status": 400,
"params": {
"image": "Invalid parameter."
},
"details": []
}
}
}
Otherwise, when making an update such as { "hide_from_listings" : false }, when the json response comes back, the value of the image key just comes back as false: { "image" : false }
Would greatly appreciate any kind of input on this issue...

postback button in dialogflow messenger cx

Hello I'm trying to create a flow in dialogflow cx, where in case of multiple options I want my user to select 1 option where all the options are buttons.
I have used the default payload but not sure how can I send back which button got clicked to my webhook and return respective info, currently if I click on button it simply open example.com, if I exclude the link it opens same page in new tab.
{
"type": "button",
"icon": {
"type": "chevron_right",
"color": "#FF9800"
},
"text": "Button text 1",
"link" : "www.example.com",
"event": {
"name": "some name",
"languageCode": "en",
"parameters": {}
}
}
For your use case, since the button response type always redirects to a page when clicked, you can consider using suggestion chips instead.
{
"richContent": [
[
{
"options": [
{
"text": "Chip 1"
},
{
"text": "Chip 2"
}
],
"type": "chips"
}
]
]
}
Suggestion chips act like a user text query when the user clicks on it, therefore, you can just create a route that can be triggered by text of the chip and get the text query from the webhook request sent to your webhook to return the respective information. For example:
Intent:
Route:
Then in your webhook, you can get the parameter value in the text field of the webhook request which you will refer to in order to create a webhook response with the respective information.
Here’s an example in Node.js using Express:
app.post("/webhook", (req, res) => {
let option = req.body.text;
let jsonResponse = {
fulfillment_response: {
messages: [
{
text: {
//fulfillment text response to be sent to the agent
text: [`You've chosen the ${option} option`]
}
}
]
}
};
res.json(jsonResponse);
});
Alternatively, you can also use entity types and assign the selected chip into a parameter that will be also sent to your webhook.
To assign the text of the chip to a parameter, the intent of the route should contain training phrases that are annotated to an entity type containing all of the options. For example:
Intent:
Entity Type:
Then in your webhook, you can get the parameter value in the intentInfo.parameters.parameter_id.resolvedValue field of the webhook request which you will refer to in order to create a webhook response with the respective information.
Here’s an example in Node.js using Express:
app.post("/webhook", (req, res) => {
let option = req.body.intentInfo.parameters.options.resolvedValue;
let jsonResponse = {
fulfillment_response: {
messages: [
{
text: {
//fulfillment text response to be sent to the agent
text: [`You've chosen the ${option} option`]
}
}
]
}
};
res.json(jsonResponse);
});
Results:
There is a simple albeit hacky way I have discover possible (tested in es). Which is to make a chip and get its element then force clicking it
We can listen to button click and I detect that it was empty button with just text. Then I use renderCustomCard to make a chip. Everything inside dialogflow messenger are hidden deep inside nested shadowRoot. But as of now its structure allow us to get the chip out to call click() on it. In effect it make it seem very the same as user manually click the chip
const dfMessenger = document.querySelector('df-messenger');
dfMessenger.addEventListener('df-button-clicked',function(event) {
if(event.detail.element.event || event.detail.element.link)
return;
dfMessenger.renderCustomCard([
{
"type": "chips",
"options": [
{
"text": event.detail.element.text
}
]
}
]);
var messageList = dfMessenger.shadowRoot.querySelector("df-messenger-chat").shadowRoot.querySelector("df-message-list").shadowRoot;
var chips = [...messageList.querySelectorAll("df-chips")].flatMap((chips) => [...chips.shadowRoot.querySelectorAll(".df-chips-wrapper>a")]).filter((a) => a.innerHTML.indexOf(event.detail.element.text) > -1);
if(chips.length > 0)
chips.slice(-1)[0].click();
});
Working for today. No guarantee they will block this method in the future. But I actually guess they would implement actual postback button in similar manner later after beta version

sequelize couldnt save array of objects into table

I sent this request which is an array of objects from reactjs app to nodejs(sequelize,mysql)backend
{
"Qusetion":"new question",
"Qusetiontype":"AddedAnswers",
"Qusetionanswers":[
{
"QuestionAnswer":"a1"
},
{
"QuestionAnswer":"a2"
}
],
"Surveyid":"9fe96b40-7704-11e9-b46f-3f2c20a71682"
}
the nodejs script
QuestionAnswer.create(req.body.Qusetionanswers.map(Answer=>{
Qusetionanswer=Answer.QuestionAnswer,
QuestionId=qid
})
).then(res=>{console.log(res)}).catch(err=>{console.log(err)})
My Problem: I got below error msg in postman when trying to send new question I searched and found that create not accept an array of objects and nothing else.so any help thanks in advance
{
"message": "this.build(...).save is not a function"
}
I would try it likes this. Creating one after one. Or are you trying to archive anything else?
req.body.Questionanswers.map(answer => {
QuestionAnswer.create({
Qusetionanswer: answer.QuestionAnswer,
QuestionId: qid
}).then(res => {console.log(res);}).catch(err => {console.log(err);}
);
});

Add member to distribution group using Azure AD API

I want to add a member to a distribution list. As apparently I can't do this using Microsoft Graph, I am trying to use Azure AD Graph API. I am using Node.js.
I am able to connect to Azure using the adal-node library. I get a token back, send requests, and get responses. (I can list groups, users, etc.).
I am following the Add Members documentation, but I am confused.
In the URL, is object_id the id of the Group to witch I want to add the member?
For myorganization, I am using the tennant_id.
Where do I specify the user data? Should I pass that in the POST? If so, whats' the format?
What is the $links in the URL?
Currently, I am doing this:
request.post(
"https://graph.windows.net/TENNANT_ID_HERE/groups/GROUP_ID_HERE/$links/members?api-version=1.6",
{
headers: {
Authorization: "Bearer " + TOKEN_HERE,
"Content-Type": "application/json"
},
form: { key: "value" } //should I put my user object here?
},
function(err, res, body) {
if (err) {
console.log("err: " + err);
} else {
console.log("res: " + JSON.stringify(res, null, 3));
}
}
);
I get the following error:
{
"odata.error": {
"code": "Request_BadRequest",
"message": {
"lang": "en",
"value": "A supported MIME type could not be found that matches the
content type of the response. None of the supported type(s) 'application/xml, text/xml,
application/json;odata=minimalmetadata;streaming=true, application/json;odata=minimalmetadata;
streaming=false, application/json;odata=minimalmetadata,
application/json;odata=fullmetadata;streaming=true,
application/json;odata=fullmetadata;streaming=false,
application/json;odata=fullmetadata,
application/json;odata=nometadata;streaming=true,
application/json;odata=nometadata;streaming=false,
application/json;odata=nometadata,
application/json;streaming=true,
application/json;streaming=false,
application/json;odata=verbose,
application/json'
matches the content type 'application/x-www-form-urlencoded'."
}
}
}
The short/most important answer is that neither Microsoft Graph or Azure AD Graph API supports distribution lists. From the documentation:
Important: You can only add members to security groups and mail-enabled security groups.
That said, this isn't technically why your call is failing here. Your code is reaching the point where it's failing due to the type of group you're working with. And while it won't help you with managing a distribution list, the following is what is actually happening.
The form: { key: "value" } option is telling request to send the payload as a URL Encoded Form (application/x-www-form-urlencoded). The API requires the payload be sent as JSON (application/json).
To send over JSON, you need to do two things:
Set the json option to true
Set the body value rather than the form value.
The proper code would look something like this:
request.post(
"https://graph.windows.net/{tenant-id}/groups/{group-id}/$links/members?api-version=1.6",
{
headers: {
Authorization: "Bearer " + TOKEN_HERE
},
json: true,
body: JSON.stringify({ url: "https://graph.windows.net/{tenant-id}/directoryObjects/{user-id}" })
},
function(err, res, body) {
if (err) {
console.log("err: " + err);
} else {
console.log("res: " + JSON.stringify(res, null, 3));
}
}
);
The $links parameter in the URI is telling the API that you're providing a link to another resource (in this case, a user record).
we could add member to a group with AD graph API.
post https://graph.windows.net/{tenantId}/groups/{groupobjectid}/$links/members?api-version=1.6
body
{
"url": "https://graph.windows.net/{tenantId}/directoryObjects/{userObjectId}"
}
Test it with Postman

error in filtered function creation on couchdb

I'm trying to follow this tutorial to filter the replication between a pouchdb and a couchdb databases
https://pouchdb.com/2015/04/05/filtered-replication.html
The problem is when I try to create the filtered function in the Fauxton webapp. In my created database, I click Design Document > New Docs and then paste the function:
{
"_id": "_design/app",
"filters": {
"by_agent": function(doc, req) {
return doc.agent === req.query.agent;
}.toString()
}
}
and when I click Create Document button, it crashes. The javascript console says
Uncaught SyntaxError: Unexpected token u in JSON at position 61
at JSON.parse ()
at t.checkDocIsValid (https://127.0.0.1:6984/_utils/dashboard.assets/js/bundle-b8e0ba71119195edb7ec64b98f53d9b9.js:529:19481)
at t.saveDoc (https://127.0.0.1:6984/_utils/dashboard.assets/js/bundle-b8e0ba71119195edb7ec64b98f53d9b9.js:529:19056)
...
how do I create the filtered function in couchDB? Maybe that isn't the procedure or I have to create it on another dababase. Thanks in advance
So what you're trying to do is use JavaScript code to create a view. Therefore, Fauxton takes only JSON as a document.
Here's how you can get the JSON from the JavaScript snippet :
//The snippet you had was a JavaScript object
//Even if it seems like a JSON object, there is a function() declaration followed by a .toString()
//By doing so, it easier to write functions instead of writing them in a raw string.
var javascriptObject = {
"_id": "_design/app",
"filters": {
"by_agent": function(doc, req) {
return doc.agent === req.query.agent;
}.toString()
}
}
console.info("You should use the following string in your Fauxton Editor:");
console.log(JSON.stringify(javascriptObject));
You should use the following string instead of the JavaScript snippet you tried:
{
"_id": "_design/app",
"filters": {
"by_agent": "function (doc, req) {\n return doc.agent === req.query.agent;\n }"
}
}

Resources