Example of Joining Tables in Azure mobile services - azure-mobile-services

I am new to azure mobile services.
As given in the documentation to join two tables .Here is the code.
mssql.query('SELECT t.text, t.complete, p.description FROM ToDoItem as t INNER JOIN Priority as p ON t.priority = p.number', {
success: function(results) {
console.log(results);
},
error: function(err) {
console.log("error is: " + err);
});
Result :
{ text: 'Take out the trash', complete: false, description: 'Critical'}
Obviously the results will be written to logs.
So how will i get the result back at my client.?
What lines should i replace with console.log(results);?

It depends, because some scripts have both a request and response passed in, while others only have access to the request.
If this is within an API script, use
response.send(200, results);
If this is within a table script, use
request.respond(200, results);

Related

Github V4 GraphQL API - audit log query

i'm trying to interact with github api v4, i want to query audit log events based on schemas available in the api. I can found a documentary about the github api here and I can see the schemas available here but there are no working examples of how to query the different schemas.
If there is someone here experience with this API, specially with the audit log schemas, I need a working example to start interacting with the audit log schemas...
for example i want to query all organization add member to team events, suppose to be in the schema TeamAddMemberAuditEntry, or remove member from org OrgRemoveMemberAuditEntry
So far I've tried to query it with node.js:
require('isomorphic-fetch');
fetch('https://api.github.com/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json',
'Authorization': 'bearer <token>',
'Accept': 'application/vnd.github.audit-log- preview+json'},
body: JSON.stringify({ query: '{ TeamAddMemberAuditEntry }' }),
})
.then(res => res.json())
.then(res => console.log(res.data));
If someone here will look for solution, after viewing the public schema this is how the query looks for getting audit-log objects, this is without the headers and the query prefix of course.
The auditLog is a union type, you can get multiple audit events by adding another "...on" block. for example here i'm getting all the orginvitemembers events
{
organization(login:"<your-org>") {
auditLog(first:2) {
edges {
node {
__typename
... on OrgInviteMemberAuditEntry {
action
actorIp
actorLogin
createdAt
userLogin
actorLocation{
country
city
}
}
}
}
}
}
}
I was after the same thing. I think your query statement is like the issue.
I came across this documentation in the GitHub blog.
https://github.blog/2019-06-21-the-github-enterprise-audit-log-api-for-graphql-beginners/
I was able to adapt the example query and come up with the following...
{
organization(login: "xyz-corp") {
auditLog(last: 10
, query: "action:org.remove_member") {
edges {
node {
... on AuditEntry {
action
actorLogin
userLogin
createdAt
user{
name
email
}
}
}
}
}
}
}
I was able to substitute the query with the following just as I would via the UI to get adds and updates.
action:org.add_member
action:org.update_member
Other audit log query items are described here
https://docs.github.com/en/organizations/keeping-your-organization-secure/reviewing-the-audit-log-for-your-organization

I want my Dialogflow bot to say a message which includes the result from a MongoDB query

I am querying a collection in MongoDB from Dialoglow Fulfillment. I then want my bot to respond with a message which includes this query. The code in the function of the Dialogflow Fulfillment is:
function readRecord(agent){
var name;
MongoClient.connect(uri, function(err, client) {
const collection = client.db("test").collection("data");
collection.find({fname: 'Example'}).toArray(function(err, result){
if (err) throw err;
console.log(result);
name = result.lname;
agent.add("Found last name: ", name);
});
client.close();
});
}
When I run this I get no response from my from the bot. When I console.log(result) the information is there but I can't seem to get the bot to say it.
The issue is that the intent handler expects you to return a Promise if you are doing any asynchronous functions - like accessing a database. The easiest way to do this is to change from using callbacks with MongoDB to using versions of the functions that return Promises, and then to return the promise.
I haven't tested, but something like this might work
return MongoClient.connect( uri )
.then( client => {
const collection = client.db("test").collection("data");
return collection.find({fname: 'Example'}).toArray();
})
.then( result => {
let name = result[0].lname;
agent.add("Found last name: "+name);
});

Express - return certain documents with named route parameters using axios

I'm having trouble communicating between the frontend and backend for a selected GET request.
I am using a React frontend with an express/mongoose setup out in the backend.
In the frontend, I do a GET call using axios for:
axios.get('/api/orders/', {
params : {
name: this.props.user.name // user name can be Bob
}
})
And in the backend I'm having a hard time understanding the correct method I would need to do to query the database (example below doesn't work). I found stuff with .select but even then I still can't get it to work:
router.get('/orders', function(req, res) {
Order.find({}).select(req.params).then(function (order) {
res.send(req.params);
})
});
I also tried doing this to see if I can even get the params to send properly and to no demise:
router.get('/orders/:name', function(req, res) {
res.send('client sent :',req.query.name);
});
The orders document model holds objects that house an ordered array and a name (type: String) attached to the object. The Mongoose scheme for the order:
const orderScheme = new Schema({
name : { type : String },
orders : { type : Array}
});
In my MongoDB, I can see all the "Master Orders" send back. Each master order has the name of who submitted it, plus all the orders within (there can be a ton of orders).
What I'm trying to exactly do is pull up all orders that have a certain name. So if I search "TestAccount", I'll get all of bob's orders. I've included an image below:
Any pointers?
Client-side:
axios.get('/api/orders/' + this.props.user.name)
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
You need to handle the Promise when resolved/rejected.
Server-side:
router.get('/orders/:name', function(req, res) {
return Order.find({name: req.params.name}).then(function(orders) {
// return orders when resolved
res.send(orders);
})
.catch(function (error) {
// handle error
console.log(error);
})
});
You did not specify a named route parameter in your route path.
You also aren't accessing the name property by using req.params only.
You should use Model.find() conditions parameter to specify which document[s] you're trying to find. Query.prototype.select() is for filtering document fields.

Transaction in orientdb and waterline

I am trying to to create transaction in waterline but I am getting this error from OrientDB:
com.orientechnologies.orient.core.command.OCommandExecutorNotFoundException: Cannot find a command executor for the command request: sql.BEGIN
Here is my code:
try {
itemsModel.query("BEGIN", function(err) { if (err) {throw new Error(err);}
itemsModel.update({id:items_ids,status:ACTIVE},{status:INACTIVE})
.exec(function(err, INA_items){ if (err) {throw new Error(err);}
if (INA_items.length != items_ids.length ) {throw new Error({err:RECORD_NOT_FOUND});}
itemsModel.query("COMMIT", function(err) { if (err) {throw new Error({err:MSG.RECORD_NOT_FOUND,title:"ITEMS"});} });
});
});
}
catch(e){
itemsModel.query("ROLLBACK", function(err) {
if (err) {return res.serverError(err);}
return res.serverError(e);
});
}
I also checked BEGIN command directly in orientdb, but same error.
The question as it stands is mixing several different concepts, I'll try to address one by one:
Waterline's API itself does not support transactions (check issue #755);
It looks like you are using sails-orientdb adapter and from it you are executing a raw SQL query;
The SQL query you are executing in the second line of your example is just BEGIN and that's where OrientDB itself is throwing an error. A transaction SQL query must be something like:
begin
let account = create vertex Account set name = 'Luke'
let city = select from City where name = 'London'
let edge = create edge Lives from $account to $city
commit retry 100
return $edge
Example taken from OrientDB docs.
Alternatively you can use transactions in a more javascript style by making use of the Oriento DB object. Assuming you are using sails-orientdb you can get the Oriento DB object like this:
var db = itemsModel.getDB();
// using oriento syntax, you can do something like
var tx = db.begin();
tx.create({
'#class': 'TestClass',
name: 'item3'
});
return tx.commit()
.then(function (results) {
console.log(results.created.length); // should be 1
});
Example taken from Oriento tests. Another good example can be found at Oriento's example folder.

Sailsjs and Associations

Getting into sails.js - enjoying the cleanliness of models, routes, and the recent addition of associations. My dilemma:
I have Users, and Groups. There is a many-many relationship between the two.
var User = {
attributes: {
username: 'string',
groups: {
collection: 'group',
via: 'users'
}
}
};
module.exports = User;
...
var Group = {
attributes: {
name: 'string',
users: {
collection: 'user',
via: 'groups',
dominant: true
}
}
};
module.exports = Group;
I'm having difficulty understanding how I would save a user and it's associated groups.
Can I access the 'join table' directly?
From an ajax call, how should I be sending in the list of group ids to my controller?
If via REST URL, is this already accounted for in blueprint functions via update?
If so - what does the URL look like? /user/update/1?groups=1,2,3 ?
Is all of this just not supported yet? Any insight is helpful, thanks.
Documentation for these blueprints is forthcoming, but to link two records that have a many-to-many association, you can use the following REST url:
POST /user/[userId]/groups
where the body of the post is:
{id: [groupId]}
assuming that id is the primary key of the Group model. Starting with v0.10-rc5, you can also simultaneously create and a add a new group to a user by sending data about the new group in the POST body, without an id:
{name: 'myGroup'}
You can currently only add one linked entity at a time.
To add an entity programmatically, use the add method:
User.findOne(123).exec(function(err, user) {
if (err) {return res.serverError(err);}
// Add group with ID 1 to user with ID 123
user.groups.add(1);
// Add brand new group to user with ID 123
user.groups.add({name: 'myGroup'});
// Save the user, committing the additions
user.save(function(err, user) {
if (err) {return res.serverError(err);}
return res.json(user);
});
});
Just to answer your question about accessing the join tables directly,
Yes you can do that if you are using Model.query function. You need to check the namees of the join tables from DB itself. Not sure if it is recommended or not but I have found myself in such situations sometimes when it was unavoidable.
There have been times when the logic I was trying to implement involved a lot many queries and it was required to be executed as an atomic transaction.
In those case, I encapsulated all the DB logic in a stored function and executed that using Model.query
var myQuery = "select some_db_function(" + <param> + ")";
Model.query(myQuery, function(err, result){
if(err) return res.json(err);
else{
result = result.rows[0].some_db_function;
return res.json(result);
}
});
postgres has been a great help here due to json datatype which allowed me to pass params as JSON and also return values as JSON