I'm trying to hit the REST endpoint by using AXIOS library and the response.data return the below in console.log:
Reseponse for console.log(response.data)
{
sqlQuery: "select type,subtype from wetrade_p2 where parent_id='69341269'",
message: '1 rows selected',
row: [ { column: [Array] } ]
}
But when I hit the same REST endpoint in postman and I can get the entire Response JSON as like below:
PostMan Output (Expected):
{
"sqlQuery": "select type,subtype from wetrade_p2 where parent_id='69341269'",
"message": "2 rows selected",
"row": [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
}
I also tried to stingify the response.data and it returned below response which is not able to parse()
Getting below response in console.log when I tried to use JSON.stringify(response.data):
sqlQuery: "select type,subtype from wetrade_p2 where parent_id=69341269"
message: "2 rows selected"
row: [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
Sample Code:
await axios[methodType](url, body, {
httpsAgent:httpsAgent,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": true
}
}).then(response => {
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response.data);
console.log(JSON.stringify(response.data))
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response);
}).catch(error => {
console.log(error);
});
You DO get the right data, just node.js doesn't display it in the console/stdout. You can use util.inspect() for a better formatted output. Try this:
const util = require('util');
// ...
console.log(util.inspect(response.data, { showHidden: false, depth: null }));
Related
I'm currently facing an issue with my datatable implemented in ReactJS. I'm retrieving data from elasticsearch and populating the datatable with it. The data retrieval process works fine without the filter applied, however, when I apply filters to the data, the datatable remains empty, even though the data _source has matching records.
The structure of the parameters I am sending is as follows:
{
pageIndex: 1,
pageSize: 10,
sort: { order: '', key: '' },
query: '',
filterData: {
analysis: [ '0', '1', '2', '3' ],
threat_level_id: [ '1', '2', '3', '4' ],
}
}
EndPoint:
POST /api/v1/events/public/list
Controller:
exports.getPublicEvents = async (req, res) => {
try {
client.ping()
const { pageIndex, pageSize, sort, query, filterData } = req.body
let esQuery = {
index: 'ns_*',
body: {
query: {
bool: {
must: [
{
match_all: {},
},
],
filter: [],
},
},
from: (pageIndex - 1) * pageSize,
size: pageSize,
},
}
if (query) {
esQuery.body.query.bool.must = [
{
match: {
'Event.info': {
query: query,
fuzziness: 'AUTO',
},
},
},
]
}
if (filterData.analysis.length > 0) {
esQuery.body.query.bool.filter.push({
terms: {
'Event.analysis': filterData.analysis,
},
})
}
if (filterData.threat_level_id.length > 0) {
esQuery.body.query.bool.filter.push({
terms: {
'Event.threat_level_id': filterData.threat_level_id,
},
})
}
let esResponse = await client.search(esQuery)
let data = esResponse.hits.hits.map((hit) => hit._source)
let total = esResponse.hits.total.value
res.status(200).json({
status: 'success',
data: data,
total: total,
})
} catch (error) {
res.status(500).json({
error: 'Error connecting to Elasticsearch',
errorMessage: error.message,
})
}
}
The controller below is without filters and it works just fine.
exports.getPublicEvents = async (req, res) => {
try {
client.ping()
const { pageIndex, pageSize, sort, query } = req.body
let esQuery = {
index: 'ns_*',
body: {
query: {
match_all: {},
},
from: (pageIndex - 1) * pageSize,
size: pageSize,
},
}
if (query) {
esQuery.body.query = {
match: {
'Event.info': {
query: query,
fuzziness: 'AUTO',
},
},
}
}
let esResponse = await client.search(esQuery)
let data = esResponse.hits.hits.map((hit) => hit._source)
let total = esResponse.hits.total.value
res.status(200).json({
status: 'success',
data: data,
total: total,
})
} catch (error) {
res.status(500).json({
error: 'Error connecting to Elasticsearch',
errorMessage: error.message,
})
}
}
ElasticSearech version: 7.17.8
Result of: console.log(JSON.stringify(esQuery))
{
"index": "INDEX_NAME",
"body": {
"query": {
"bool": {
"must": [{ "match_all": {} }],
"filter": [
{ "terms": { "Event.analysis": ["0", "1", "2"] } },
{ "terms": { "Event.threat_level_id": ["1", "2", "3", "4"] } }
]
}
},
"from": 0,
"size": 10
}
}
Data in elascticsearch schema
{
"#version": "1",
"#timestamp": "2023-02-01T14:43:09.997Z",
"Event": {
"info": ".......................",
"description": ".......................",
"analysis": 0,
"threat_level_id": "4",
"created_at": 1516566351,
"uuid": "5a64f74f0e543738c12bc973322",
"updated_at": 1675262417
}
}
Index Mapping
{
"index_patterns": ["INDEX_NAME"],
"template": "TEMPLATE_NAME",
"settings": {
"number_of_replicas": 0,
"index.mapping.nested_objects.limit": 10000000
},
"mappings": {
"dynamic": false,
"properties": {
"#timestamp": {
"type": "date"
},
"Event": {
"type": "nested",
"properties": {
"date_occured": {
"type": "date"
},
"threat_level_id": {
"type": "integer"
},
"description": {
"type": "text"
},
"is_shared": {
"type": "boolean"
},
"analysis": {
"type": "integer"
},
"uuid": {
"type": "text"
},
"created_at": {
"type": "date"
},
"info": {
"type": "text"
},
"shared_with": {
"type": "nested",
"properties": {
"_id": {
"type": "text"
}
}
},
"updated_at": {
"type": "date"
},
"author": {
"type": "text"
},
"Attributes": {
"type": "nested",
"properties": {
"data": {
"type": "text"
},
"type": {
"type": "text"
},
"uuid": {
"type": "text"
},
"comment": {
"type": "text"
},
"category": {
"type": "text"
},
"value": {
"type": "text"
},
"timestamp": {
"type": "date"
}
}
},
"organisation": {
"type": "nested",
"properties": {
"name": {
"type": "text"
},
"uuid": {
"type": "text"
}
}
},
"Tags": {
"type": "nested",
"properties": {
"color": {
"type": "text"
},
"name": {
"type": "text"
}
}
},
"TLP": {
"type": "nested",
"properties": {
"color": {
"type": "text"
},
"name": {
"type": "text"
}
}
}
}
}
}
}
}
Event is a nested field, so you need to use nested queries, like this:
{
"index": "INDEX_NAME",
"body": {
"query": {
"bool": {
"must": [{ "match_all": {} }],
"filter": [
{
"nested": {
"path": "Event",
"query": {"terms": { "Event.analysis": ["0", "1", "2"] }}
}
},
{
"nested": {
"path": "Event",
"query": {"terms": { "Event.threat_level_id": ["1", "2", "3", "4"] }}
}
}
]
}
},
"from": 0,
"size": 10
}
}
The following code gives me the error "Invalid request payload. Refer to the REST API documentation and try again" when is executed and I dont know where the error is
const bodyData =
`"fields": {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "PRB"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}`;
fetch('https://mysite.atlassian.net/rest/api/3/issue', {
method: 'POST',
headers: {
'Authorization': `Basic ${Buffer.from('myemail#gmail.com:mytoken').toString('base64')}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: bodyData
}).then(response => {
console.log(
`Response: ${response.status} ${response.statusText}`
);
return response.text();
}).then(text => console.log(text)).catch(err => console.error(err));
Problem
Your bodyData is not a valid json
Solution
Wrap it with {}
`{
fields: {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "LOD"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}
}`
P.S.
You would find this error if you would use JSON.stringify with an object instead of a string.
const bodyData = JSON.stringify(
{
fields: {
"summary": "Summit 2019 is awesome!",
"issuetype": {
"name": "Task"
},
"project": {
"key": "LOD"
},
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "This is the description.",
"type": "text"
}
]
}
]
}
}
});
Here is the data representation in mongodb :
{
"_id": {
"$oid": "60754054fa887e14c4569a94"
},
"details": [{
"label": "Asset title",
"type": "text",
"id": "text-1617189723969",
"value": "S1",
"rawValue": "S1"
}, {
"label": "Total Cost",
"type": "number",
"id": "number-1618296818377",
"value": "1500",
"rawValue": "1500"
}, {
"label": "Possession Status",
"type": "radio",
"id": "radio-1617189728809",
"value": "Available",
"rawValue": "available"
}, {
"label": "Estimated Monthly Rent",
"type": "number",
"id": "number-1617189737553",
"value": "200",
"rawValue": "200"
}],
"status": "Approved",
"createdAt": {
"$date": "2021-04-13T06:55:16.843Z"
},
"__v": 0
},
{
"_id": {
"$oid": "60756c279cdd25019c6c3707"
},
"details": [{
"label": "Asset title",
"type": "text",
"id": "text-1617189723969",
"value": "S2",
"rawValue": "S2"
}, {
"label": "Total Cost",
"type": "number",
"id": "number-1618296818377",
"value": "280",
"rawValue": "280"
}, {
"label": "Possession Status",
"type": "radio",
"id": "radio-1617189728809",
"value": "Available",
"rawValue": "available"
}, {
"label": "Estimated Monthly Rent",
"type": "number",
"id": "number-1617189737553",
"value": "500",
"rawValue": "500"
}],
"status": "Approved",
"createdAt": {
"$date": "2021-04-13T10:02:15.701Z"
},
"__v": 0
},
{
"_id": {
"$oid": "60756d33af10052394f24e5c"
},
"details": [{
"label": "Asset title",
"type": "text",
"id": "text-1617189723969",
"value": "S3",
"rawValue": "S3"
}, {
"label": "Total Cost",
"type": "number",
"id": "number-1618296818377",
"value": "100",
"rawValue": "100"
}, {
"label": "Possession Status",
"type": "radio",
"id": "radio-1617189728809",
"value": "Available",
"rawValue": "available"
}, {
"label": "Estimated Monthly Rent",
"type": "number",
"id": "number-1617189737553",
"value": "300",
"rawValue": "300"
}],
"status": "Approved",
"createdAt": {
"$date": "2021-04-13T10:06:43.560Z"
},
"__v": 0
}
For example : I am trying to sort the documents where I have to pick the value of that object from details array whose label is "Total Cost" and apply sorting based on "Total cost" value.
MY CODE IMPLEMENTATION :
assetCtrl.getApprovedAsset = async (req, res) => {
try {
let { sorting, sortingtype } = req.query;
let perPage = Number(req.query.perpage ? req.query.perpage : 0);
let page = Number(req.query.page ? req.query.page : 0);
if (typeof perPage !== 'undefined' && perPage !== '' && perPage > 0 &&
typeof page !== 'undefined' && page !== '' && page > 0) {
let skippage = (perPage * page) - perPage;
let filter = {
status: "Approved",
}
let sortObj = {}
let sorttype = (sortingtype === 'asc') ? 1 : -1;
if (sorting !== '') {
switch (sorting) {
case 'cost' :
sortObj.details.value = sorttype;
break;
case 'monthly_rent' :
sortObj.details.value = sorttype;
break;
case 'createdAt':
sortObj.createdAt = sorttype;
break;
}
} else {
sortObj.details.value = 1;
}
AddAssets.aggregate([
{
"$project": {
createdAt: 1,
userid: 1,
details: 1,
status: 1
}
},
{
"$match": filter
},
// {
// "$match": {
// details: {
// "$elemMatch": {
// label: "Total Cost"
// }
// }
// }
// },
// ]).sort({ "details.value": 1 }).skip(skippage).limit(perPage)
]).sort({ sortObj}).skip(skippage).limit(perPage)
.exec((err, assetList) => {
if (err) {
res.status(400).json({ status: false, message: err.message })
} else {
res.status(200).json({
status: true,
message: "success",
assetList: assetList,
current: page,
})
}
})
}
} catch (error) {
res.status(500).json({ status: false, message: "Internal Server Error" })
}
}
Note: I also tried excluding sortObj and implemented commented code .
Use $set with https://docs.mongodb.com/manual/reference/operator/aggregation/filter/ to reduce the array to the single document with the total cost field, then $sort on this field.
Using acumatica web services (json REST api), how can I set the TaxZone when I create an Invoice. Here's a sample json put request:
{
"Date": { "value": "12/23/2019" },
"DueDate": { "value": "12/23/2019" },
"Customer": { "value": "12345" },
"Type": { "value": "Invoice" },
"LinkBranch": { "value": "MYBRANCH" },
"FinancialDetails": {
"TaxZone": { "value": "1" }
}
}
I have tried that, tried TaxZoneId, tried posting without using FinancialDetails object... nothing seems to work.
The easiest way to get the correct structure of the JSON is to send get request with "expand" parameter like below:
http://localhost/ACU19200/entity/Default/18.200.001/SalesInvoice/Invoice|AR007541?$expand=FinancialDetails
This will return you the Invoice record with Financial Details, like below:
{
"id": "7bd77116-dcf1-e911-b312-fc017c8c8936",
"rowNumber": 1,
"note": "",
"Amount": {
"value": 2385.0000
},
"Balance": {
"value": 1910.0000
},
"CashDiscount": {
"value": 0.0000
},
"CreditHold": {
"value": false
},
"Currency": {
"value": "USD"
},
"CustomerID": {
"value": "ABARTENDE"
},
"CustomerOrder": {},
"Date": {
"value": "2019-10-18T00:00:00-07:00"
},
"Description": {},
"DueDate": {
"value": "2019-11-17T00:00:00-08:00"
},
"FinancialDetails": {
"id": "1b004ff5-496f-463e-8b37-f6c74a044482",
"rowNumber": 1,
"note": null,
"BatchNbr": {
"value": "AR006749"
},
"Branch": {
"value": "PRODWHOLE"
},
"CustomerTaxZone": {},
"custom": {},
"files": []
},
"Hold": {
"value": false
},
"Project": {
"value": "X"
},
"ReferenceNbr": {
"value": "AR007541"
},
"Status": {
"value": "Open"
},
"Type": {
"value": "Invoice"
},
"VATExemptTotal": {
"value": 0.0000
},
"VATTaxableTotal": {
"value": 0.0000
},
"custom": {},
"files": []
}
Now after we have the structure we need to remove the redundant fields from the request and send the PUT request with the JSON like below (of course in your case you need to also provide invoice details and other information):
{
"CreditHold": {
"value": false
},
"Currency": {
"value": "USD"
},
"CustomerID": {
"value": "ABARTENDE"
},
"Description": {
"value" : "Test Invoice"
},
"Hold": {
"value": false
},
"Status": {
"value": "Open"
},
"Type": {
"value": "Invoice"
},
"FinancialDetails": {
"CustomerTaxZone": {
"value": "AVALARA"
}
}
}
You will need to extend the default endpoint if you need to work with AR Invoice (Default/18.200.001/Invoice) because it doesn't contain CustomerTaxZone by default.
You can do it as shown below and then just send CustomerTaxZone as "TaxZone" on the top level.
I am providing users with a response on an audio only device (e.g. google home), when I respond with a textToSpeech field within a simpleResponse, the speech is not read out in the simulator.
Has anyone experienced this and know how to fix?
I've tried different response types but none of them read out the textToSpeech field.
Also tried ticking/unticking end conversation toggle in Dialogflow and expectUserInput true/false when responding with JSON to no avail.
The response is currently fulfilled by a webhook which responds with JSON v2 fulfilment blob and the simulator receives the response with no errors but does not read it out.
RESPONSE -
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "Here are the 3 closest restaurants that match your criteria,"
}
}
]
}
}
}
}
REQUEST -
{
"responseId": "404f3b65-73a5-47db-9c17-0fc8b31560a5",
"queryResult": {
"queryText": "actions_intent_NEW_SURFACE",
"parameters": {},
"allRequiredParamsPresent": true,
"outputContexts": [
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/findrestaurantswithcuisineandlocation-followup",
"lifespanCount": 98,
"parameters": {
"location.original": "Shoreditch",
"cuisine.original": "international",
"cuisine": "International",
"location": {
"subadmin-area": "Shoreditch",
"subadmin-area.original": "Shoreditch",
"subadmin-area.object": {}
}
}
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_account_linking"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_audio_output"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/google_assistant_input_type_voice"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_capability_media_response_audio"
},
{
"name": "projects/my-project/agent/sessions/sessionId/contexts/actions_intent_new_surface",
"parameters": {
"text": "no",
"NEW_SURFACE": {
"#type": "type.googleapis.com/google.actions.v2.NewSurfaceValue",
"status": "CANCELLED"
}
}
}
],
"intent": {
"name": "projects/my-project/agent/intents/0baefc9d-689c-4c33-b2b8-4e130f626de1",
"displayName": "Send restaurants to mobile"
},
"intentDetectionConfidence": 1,
"languageCode": "en-us"
},
"originalDetectIntentRequest": {
"source": "google",
"version": "2",
"payload": {
"isInSandbox": true,
"surface": {
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.MEDIA_RESPONSE_AUDIO"
},
{
"name": "actions.capability.ACCOUNT_LINKING"
}
]
},
"requestType": "SIMULATOR",
"inputs": [
{
"rawInputs": [
{
"query": "no",
"inputType": "VOICE"
}
],
"arguments": [
{
"extension": {
"#type": "type.googleapis.com/google.actions.v2.NewSurfaceValue",
"status": "CANCELLED"
},
"name": "NEW_SURFACE"
},
{
"rawText": "no",
"textValue": "no",
"name": "text"
}
],
"intent": "actions.intent.NEW_SURFACE"
}
],
"user": {
"userStorage": "{\"data\":{}}",
"lastSeen": "2019-04-12T14:31:23Z",
"locale": "en-US",
"userId": "userID"
},
"conversation": {
"conversationId": "sessionId",
"type": "ACTIVE",
"conversationToken": "[\"defaultwelcomeintent-followup\",\"findrestaurantswithcuisineandlocation-followup\",\"findrestaurantswithcuisineandlocation-followup-2\"]"
},
"availableSurfaces": [
{
"capabilities": [
{
"name": "actions.capability.AUDIO_OUTPUT"
},
{
"name": "actions.capability.SCREEN_OUTPUT"
},
{
"name": "actions.capability.WEB_BROWSER"
}
]
}
]
}
},
"session": "projects/my-project/agent/sessions/sessionId"
}
I expect the simulator to read out the result of textToSpeech but currently does not.