I don't understand how to get standard JSON back from an orientjs query. I see people talking about "serializing" the result, but I don't understand why or how to do that. There is a toJSON() method, but i only see it being used with fetchplans etc...
I am trying to pipe a stream to a csv file and it isn't working properly because of the incorrect JSON format.
I would love an explanation of how and when to serialize. :-)
My Query:
return db.query(
`SELECT
id,
name,
out('posted_to').name as page,
out('posted_to').id as page_id,
out('posted_to').out('is_language').name as language,
out('posted_to').out('is_network').name as network
FROM post
WHERE posted_at
BETWEEN
'${since}'
AND
'${until}'
UNWIND
page,
page_id,
language,
network
`
My Result:
[ { '#type': 'd',
id: '207109605968597_1053732754639607',
name: '10 maneiras pelas quais você está ferindo seus relacionamentos',
page: 'Eu Amo o Meu Irmão',
page_id: '207109605968597',
language: 'portuguese',
network: 'facebook',
'#rid': { [String: '#-2:1'] cluster: -2, position: 1 },
'#version': 0 },
{ '#type': 'd',
id: '268487636604575_822548567865143',
name: '10 maneiras pelas quais você está ferindo seus relacionamentos',
page: 'Amo meus Filhos',
page_id: '268487636604575',
language: 'portuguese',
network: 'facebook',
'#rid': { [String: '#-2:3'] cluster: -2, position: 3 },
'#version': 0 }]
This is my dataset:
Query:
db.select('id','code').from('tablename').where({deleted:true}).all()
.then(function (vertex) {
console.log('Vertexes found: ');
console.log(vertex);
});
Output:
Vertexes found:
[ { '#type': 'd',
id: '6256650b-f5f2-4b55-ab79-489e8069b474',
code: '4b7d99fa-16ed-4fdb-9baf-b33771c37cf4',
'#rid': { [String: '#-2:0'] cluster: -2, position: 0 },
'#version': 0 },
{ '#type': 'd',
id: '2751c2a0-6b95-44c8-966a-4af7e240752b',
code: '50356d95-7fe7-41b6-b7d9-53abb8ad3e6d',
'#rid': { [String: '#-2:1'] cluster: -2, position: 1 },
'#version': 0 } ]
If I add the instruction JSON.stringify():
Query:
db.select('id','code').from('tablename').where({deleted:true}).all()
.then(function (vertex) {
console.log('Vertexes found: ');
console.log(JSON.stringify(vertex));
});
Output:
Vertexes found:
[{"#type":"d","id":"6256650b-f5f2-4b55-ab79-489e8069b474","code":"4b7d99fa-16ed-
4fdb-9baf-b33771c37cf4","#rid":"#-2:0","#version":0},{"#type":"d","id":"2751c2a0
-6b95-44c8-966a-4af7e240752b","code":"50356d95-7fe7-41b6-b7d9-53abb8ad3e6d","#ri
d":"#-2:1","#version":0}]
Hope it helps
I found a way that worked for me. instead of using :
db.query()
i used http request in node to query on database. on OrientDB Document also said you get only JSON format in result. this way if you query in database you will always get a valid JSON.
for making a http request i used request module.
this is a sample that worked for me :
var request = require("request");
var auth = "Basic " + new Buffer("root" + ":" + "root").toString("base64")
request(
{
url : encodeURI('http://localhost:2480/query/tech_graph/sql/'+queryInput+'/20'),
headers : {
"Authorization" : auth
}
},
function (error, response, body) {
console.log(body);
return body;
}
);
Related
I have a Monday.com board (table). I want to add a new item (row) including the column values. Columns are of type:
email
color
timeline
date
hour
text
I want to create the GraphQL API call in JavaScript on the browser.
The issue is that you need to JSON encode the column_values attribute value and escape it since it is within the query value.
Example
The msg function logs the message.
The following was tested as JavaScript running in a browser. The Monday.com API supports CORS.
let colValues = {
to: {text: "Larry K",
email: "larry#example.com"},
status: {index:1},
timeline: {to: "2022-12-28", from: "2022-12-02"},
date: {date: "2022-12-01"},
hour: {hour:12, minute:0},
text6: "12345-67890-ABCD"
};
let req = {query:
`mutation {create_item (
board_id: ${mon_boardId},
group_id: ${mon_groupId},
item_name: "New from JS",
column_values: ${JSON.stringify(JSON.stringify(colValues))}
) {
id
}}`};
const r = await callMondayApi(req);
....
/*
* Makes a Monday.com API call with JSON request/results
*/
async function callMondayApi(req) {
let body = JSON.stringify(req, null, 4);
try {
let headers = new Headers({
Accept: `application/json`,
Authorization: `${mon_token}`,
"Content-Type": "application/json",
});
let results = await fetch("https://api.monday.com/v2", {
method: "POST",
mode: "cors",
headers: headers,
body: body
});
if (results && results.ok) {
return await results.json();
} else {
const res = await results.text();
errMsg(
`Problem while making Monday API call. ` +
`Error: ${results ? results.statusText : "no response"}.` +
res
);
return false;
}
} catch (e) {
errMsg(`Problem while making Monday API call. ` + `Error: ${e.toString()}.`);
return false;
}
}
Some details
Per the GraphQL docs, the POST JSON structure is
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}
In other words, the query/mutation is sent as a string. But within that string, the Monday.com column_values value is a JSON string!
I'm trying to call createConversation function of CCAI insights SDK #google-cloud/contact-center-insights but getting below error
ERROR ==> Error: 3 INVALID_ARGUMENT: Request contains an invalid argument.
What would be the correct request payload? I'm not able to find sample request payload for this function.
I'm using below code:
const [conversation] = await client.createConversation({
parent: client.locationPath(projectId, 'us-central1'),
conversation: {
medium: 'CHAT',
name: 'TestModel',
transcript: {
transcriptSegments: [{
segmentParticipant: {
role: 'HUMAN_AGENT',
userId: '1234'
},
text: 'Thank you for calling IBC, how can I help you today?',
confidence: 0.90,
sentiment: {
magnitude: 0.2,
score: 0.9
},
}]
}
}
});
console.info(`Created `, conversation.name);
Note: It's working for below github code but I need to send the payload in transcript format.
ccai-insight-github code
And even if we store the conversation in Storage bucket, what would be the format?
Thanks
Hi I followed this Serverless + AWS REST API tutorial and it went great, I got it to work.
Now, I'm trying to modify it but have hit a wall while trying to submit data into the DynamoDB table.
Using Postman to submit a valid JSON object I get a 502 response. If I test the function in Lambda, I get the following error:
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token o in JSON at position 1",
"trace": [
"SyntaxError: Unexpected token o in JSON at position 1",
" at JSON.parse (<anonymous>)",
" at Runtime.module.exports.submit [as handler] (/var/task/api/interview.js:11:28)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)",
" at process._tickCallback (internal/process/next_tick.js:68:7)"
]
}
After searching for solutions, what I found out is that it seem like the event that is being passed as JSON.parse(event)is undefined.
Here's the serverless.yml:
service: interview
frameworkVersion: ">=1.1.0 <2.0.0"
provider:
name: aws
runtime: nodejs10.x
stage: dev
region: us-east-1
environment:
INTERVIEW_TABLE: ${self:service}-${opt:stage, self:provider.stage}
INTERVIEW_EMAIL_TABLE: "interview-email-${opt:stage, self:provider.stage}"
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
Resource: "*"
resources:
Resources:
CandidatesDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
-
AttributeName: "id"
AttributeType: "S"
KeySchema:
-
AttributeName: "id"
KeyType: "HASH"
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
StreamSpecification:
StreamViewType: "NEW_AND_OLD_IMAGES"
TableName: ${self:provider.environment.INTERVIEW_TABLE}
functions:
interviewSubmission:
handler: api/interview.submit
memorySize: 128
description: Submit interview information and starts interview process.
events:
- http:
path: interviews
method: post
and the interview.js
'use strict';
const uuid = require('uuid');
const AWS = require('aws-sdk');
AWS.config.setPromisesDependency(require('bluebird'));
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.submit = (event, context, callback) => {
const requestBody = JSON.parse(event);
const fullname = requestBody.fullname;
const email = requestBody.email;
const test = requestBody.test;
const experience = requestBody.experience;
if (typeof fullname !== 'string' || typeof email !== 'string' || typeof experience !== 'number') {
console.error('Validation Failed');
callback(new Error('Couldn\'t submit interview because of validation errors.'));
return;
}
submitInterviewP(interviewInfo(fullname, email, experience, test))
.then(res => {
callback(null, {
statusCode: 200,
body: JSON.stringify({
message: `Sucessfully submitted interview with email ${email}`,
interviewId: res.id
})
});
})
.catch(err => {
console.log(err);
callback(null, {
statusCode: 500,
body: JSON.stringify({
message: `Unable to submit interview with email ${email}`
})
})
});
};
const submitInterviewP = interview => {
console.log('Submitting interview');
const interviewInfo = {
TableName: process.env.INTERVIEW_TABLE,
Item: interview,
};
return dynamoDb.put(interviewInfo).promise()
.then(res => interview);
};
const interviewInfo = (fullname, email, experience,test) => {
const timestamp = new Date().getTime();
return {
id: uuid.v1(),
fullname: fullname,
email: email,
experience: experience,
test: test,
submittedAt: timestamp,
updatedAt: timestamp,
};
};
If I replace the event param for a valid JSON object and then deploy again. I'm able to successfully insert the object into dynamoDB.
Any clues? Please let me know if there's anything I missing that could help.
Thanks!
API Gateway stringify the request body in event's body property.
Currently you are trying to parse event object const requestBody = JSON.parse(event); which is wrong. You need to parse event.body property:
const requestBody = JSON.parse(event.body);
I have a Node OPC Server which I connect to with a Qt application using the QtOpcUa client library.
On my server I define a method that's basically a crude historic access request as HDA support is not yet available, it takes in a start_date and end_date then queries a database for the relevant values which it returns in an array.
It looks a bit like this:
const deviceTrends = namespace.addObject({
organizedBy: deviceObject,
browseName: strings.TREND_NODE
})
const method = namespace.addMethod(deviceTrends,{
nodeId: strings.NSI + part.name + "-Trend",
browseName: part.name + "-Trend",
inputArguments: [
{
name:"start_date",
description: { text: "Trend Start Date" },
dataType: opcua.DataType.DateTime
},{
name:"end_date",
description: { text: "Trend End Date" },
dataType: opcua.DataType.DateTime
}
],
outputArguments: [{
name:"Trend",
description:{ text: "Trend Data from start_date to end_date" },
dataType: opcua.DataType.String ,
valueRank: 1
}]});
method.bindMethod(function(inputArguments,context,callback) {
console.log("called")
const start = inputArguments[0].value;
const end = inputArguments[1].value;
console.log("Start: ", start);
console.log("End: ", end);
let sql = `SELECT Date date,
Name name,
Value value
FROM Trends
WHERE DateTime >= ? AND DateTime <= ?`;
var result = []
db.each(sql, [start, end], (err, row) =>
{
result.push(`${row.date}: ${row.name} - ${row.value}`)
})
console.log(result)
const callMethodResult = {
statusCode: opcua.StatusCodes.Good,
outputArguments: [{
dataType: opcua.DataType.String,
arrayType: opcua.VariantArrayType.Array,
value :result
}]
};
callback(null,callMethodResult);});}
I can see this in a client such as Prosys and call the method which works okay:
However I can't seem to call this method from Qt, I've cut out the packaging of arguments and the result handler (it just lists out the received params):
QOpcUaNode* n = devices[deviceName].client->node("ns=1;s=Speed-Trend");
connect(n, &QOpcUaNode::methodCallFinished, [this, deviceName](QString methodNodeId, QVariant result, QOpcUa::UaStatusCode status)
{
qDebug() << " Response received ";
this->handleNodeTrendResponse(deviceName, methodNodeId, result, status);
});
n->callMethod(n->nodeId(), args);
Trace:
Requesting Trend: From QDateTime(2018-10-07 13:13:56.766 BST Qt::TimeSpec(LocalTime)) TO QDateTime(2018-10-07 13:14:05.390 BST Qt::TimeSpec(LocalTime))
qt.opcua.plugins.open62541: Could not call method: BadNodeIdInvalid
Response received [Output from method result handler]
Device Name: "speed-device"
Method Node Id: "ns=1;s=Speed-Trend"
Result: QVariant(Invalid)
Result to List: << ()
Status: QOpcUa::UaStatusCode(BadNodeIdInvalid)
I also can't seem to find the method on other clients too, this is from an OPC UA Client application on my phone which shows nothing under the Trends object:
Everything else seems accessible, I can request variables, setup monitoring all fine.
Is there something I'm just missing here or is it an issue with QtOpcUa and other clients?
I can work around this by creating variables instead to capture input and output arguments and a boolean to represent a method call but it's a lot neater to tie everything up in a single method.
Thanks
While trying to update a document I'm getting the above error for the field timesToDisplay.
MongoDB version 2.6.7.
The whole model:
msg = {
'name': '',
'template': '',
'displayDurInMilliSec': 0,
'timesToDisplay': [],
'images': [],
'texts': [],
'screen': []
}
I guess I will be getting the same error with the other 3 array fields.
I've tried using $set but sill getting the same error.
The code:
function updateMessage(msg) {
var conditions = {_id: msg._id}
, update = { 'name': msg.name,
'template': msg.template,
'displayDurInMilliSec': msg.displayDurInMilliSec,
'timesToDisplay': msg.timesToDisplay,
'images': msg.images,
'texts': msg.texts,
'screen': msg.screen
}
messageModel.update(conditions, update, callback);
function callback(err, numAffected) {
if (!err) console.log(numAffected)
else console.log(err)
}
}
EDIT: The msg parameter is a document in itself:
{ _id: '557d58abd54955480db6694f',
name: 'msg99',
timesToDisplay: [ { startDate: '2015-06-19T21:00:00.000Z',
'$$hashKey': 'object:214',
endDate: '2015-06-25T21:00:00.000Z',
daysOfTheWeek: [Object],
startTimeOfDay: '11',
endTimeOfDay: '13' } ],
images: [],
texts: [],
screen: [ 1 ],
'$$hashKey': 'object:54',
displayDurInMilliSec: '40189',
template: 'templates/Template2.html' }
The $$hashkey field is added by AngularJS when working with ngRepeat or ngOptions. In the case of ngRepeat you can change the repeat string by appending track by $index to it. For using ngOptions you'll have to filter out that field yourself. AngularJS provides a quick solution for filtering it out: angular.toJson. This will filter out all fields prefixed with two dollar signs. Check out the documentation.
I realize that this isn't a MongoDB answer, but this specific error ($$hashkey), is usually due to AngularJS.