I am using const google = require('googleapis'); to stream into google bigquery but now when I want to select my database I am puzzled.
Looking into the documentation I need to do use bigquery.jobs.query but I don`t understand where the actual select should be placed.
var query = `select 1 `;
bqBooking.auth = jwtClient;
bigquery.jobs.query(bqBooking, function (err, rows) {
if (err) {
return callback(err);
}
printExample(rows);
callback(null, rows);
});
/**
* Run an example query.
*
* #param {Function} callback Callback function.
*/
function queryExample (callback) {
var query = 'SELECT TOP(corpus, 10) as title, COUNT(*) as unique_words\n' +
'FROM [publicdata:samples.shakespeare];';
bigquery.query(query, function (err, rows) {
if (err) {
return callback(err);
}
printExample(rows);
callback(null, rows);
});
}
https://cloud.google.com/bigquery/create-simple-app-api
Can pass query as parameter in 'Request Body' of bigQuery.jobs.query example as shown in link Please use 'Try this API' option in 2nd link.
var google = require('googleapis');
var bigquery = google.bigquery('v2');
authorize(function(authClient) {
var request = {
// Project ID of the project billed for the query
projectId: '', // TODO: Update placeholder value.
resource: {
// TODO: Add desired properties to the request body.
"query": "Select channel, sum(totalRequests) from
conversation_logs.RequestSummary WHERE timeStamp >
TIMESTAMP('2017-09-03 00:00:00 UTC') Group by channel;",
"maxResults": 1,
"useLegacySql": false
},
auth: authClient
};
bigquery.jobs.query(request, function(err, response) {
if (err) {
console.log(err);
return;
}
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
});
});
function authorize(callback) {
google.auth.getApplicationDefault(function(err, authClient)) {
if (err) {
console.log('authentication failed: ', err);
return;
}
if (authClient.createScopedRequired &&
authClient.createScopedRequired()) {
var scopes = ['https://www.googleapis.com/auth/cloud-
platform'];
authClient = authClient.createScoped(scopes);
}
callback(authClient);
});
}
Related
I have written my first Lambda to handle an Alexa Skill.
My problem is that the call to the database is clearly asynchronous (I can tell from the order the Console.log messages appear in the Cloud Log.
Here is my Handler.
How do I make it so the return happens after the data is got from the database?
const RemindMeHandler = {
canHandle(handlerInput) {
const request = HandlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& request.intent.name === 'RemindMeIntent');
},
handle(handlerInput) {
console.log('Started Reminder');
var thing="Nothinbg";
/* ========== Read dB ========== */
const params =
{
TableName: 'ItemsToRecall',
Key: {
'Slot': {S: '1'}
},
};
readDynamoItem(params, myResult=>
{
console.log('Reminder Results: ' + myResult.data);
thing="Captain";
console.log('thing 1: ' + thing);
});
console.log('Ended Reminder');
function readDynamoItem(params, callback)
{
var AWS = require('aws-sdk');
AWS.config.update({region: 'eu-west-1'});
var docClient = new AWS.DynamoDB();
console.log('Reading item from DynamoDB table');
docClient.getItem(params, function (err, data)
{
if (err) {
callback(err, data);
} else {
callback('Worked', data);
}
});
}
/* ========== Read dB End ========== */
console.log('thing 2: ' + thing);
return handlerInput.responseBuilder
.speak(REMINDER_ACKNOWLEDGE_MESSAGE + thing)
.getResponse();
}
};
/* ========== Remind Handler End ========== */
You can wrap the asynchronous and return a promise and then use async/await syntax to get the data. You can check the below. Do note it's not tested.
const RemindMeHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "LaunchRequest" ||
(handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "RemindMeIntent")
);
},
async handle(handlerInput) {
console.log("Started Reminder");
let thing = "Nothinbg";
const params = {
TableName: "ItemsToRecall",
Key: {
Slot: { S: "1" }
}
};
const data = await readDynamoItem(params);
console.log("Reminder Results: ", data);
thing = "Captain";
let speechText = thing;
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.getResponse();
}
};
function readDynamoItem(params) {
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-west-1" });
const docClient = new AWS.DynamoDB();
console.log("Reading item from DynamoDB table");
return new Promise((resolve, reject) => {
docClient.getItem(params, function(err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
My lambda function uses the method
ddb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log("SUBMITTED DATA"); // successful response
});
with my params being correctly formatted to my table. No error is shown in my logs, however "SUBMITTED DATA" does not appear in the logs either, and the data is not put into my DynamoDB table. Any idea on what might be causing this problem? Heres my complete function:
const TrackHabitIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'TrackHabitIntent';
},
handle(handlerInput) {
ddb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log("SUBMITTED DATA"); // successful response
});
const speechText = "That's awesome! I'll add today to your streak of 4 days";
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.withSimpleCard('Hello World', speechText)
.getResponse();
}};
exports.handler = function (event, context) {
if (!skill) {
skill = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
HelpIntentHandler,
HelpMeIntentHandler,
TrackHabitIntentHandler,
NewHabitIntentHandler,
CancelAndStopIntentHandler,
SessionEndedRequestHandler,
)
.addErrorHandlers(ErrorHandler)
.create();
}
return response;
};
Thanks
Please check this code to add data in dynamoDB that can help you.
let putParams = {
TableName: tableName,
Item: {
'Id': {
S: Id
},
'name': {
S: name
}
},
ConditionExpression: 'attribute_exists(Id)'
};
dynamoDb.putItem(putParams, function (err, data) {
if (err) {
console.log('failure:put data from Dynamo error', err);
reject(err);
} else {
console.log('success:put data from Dynamo data');
resolve(data);
}
});
I've overridden an action in the controller that was generated from a blueprint API in Sails.JS.
I used the create action. Now I can't get a Sails.JS socket event from that action anymore, however, other actions are working fine.
io.socket.on('posts', function gotHelloMessage(data) {
console.log('Post!', data);
});
io.socket.get('/posts', function gotResponse(body, response) {
console.log('Posts: ', body);
})
What's the way to implement so that the create action also generates the event with my newly implemented actions?
create: function(req, res) {
if (
!_.has(req.body, "title") ||
!_.has(req.body, "body") ||
!_.has(req.body, "category")
) {
return res.serverError("No field should be empty.");
}
var uploadPath = "../../assets/posts";
return req
.file("thumbnail")
.upload({ dirname: uploadPath }, async function(err, uploadedFiles) {
if (err) return res.serverError(err);
let post;
try {
post = await Posts.create({
title: req.body.title,
body: req.body.body,
category: req.body.category,
thumbnail:
uploadedFiles.length === 0
? ""
: uploadedFiles[0].fd.split("/").reverse()[0]
}).fetch();
return res.json({ result: post });
} catch (err) {
return res.json({ error: err });
}
});
}
function changeData(auth,sheetId) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.update({
auth: auth,
spreadsheetId: sheetId,
range: 'Sheet1!D6',
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["abc"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}
I can get the above function to work and it changes the value just fine but the below function doesnt return value and says 0 rows retrieved. what am i doing wrong?
function read(auth,sheet_id)
{
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: sheet_id,
range: 'Sheet1!D6'
}, function(err, result) {
if(err) {
// Handle error
console.log(err);
} else {
var numRows = result.values ? result.values.length : 0;
console.log('%d rows retrieved.', numRows);
}
});
}
If you are using googleapis after the version of v26.0.1 (now it's 32.0.0.), in your script, you can retrieve the data by result.data. So how about the following modification?
From :
var numRows = result.values ? result.values.length : 0;
To :
var numRows = result.data.values ? result.data.values.length : 0;
I got problem while I move into https://github.com/DaftMonk/generator-angular-fullstack.
Before my project was working. Here is code for frontend and backend part related to comment.
I am getting all time error 404. I don't know why I cannot find following path.
POST http://localhost:9000/api/providers/554a1dba53d9ca8c2a2a31ff/posts/554b1726f1116e00256e3d82/comments 404 (Not Found)
I am struggling couple of days to discover which part of my code have problem but I couldn't realize that.
server side
in comment.controller
// Creates a new comment in the DB.
exports.create = function(req, res) {
console.log('i ma inside api');
Post.findById(req.originalUrl.split('/')[3], function (err, post) { //here can not find post at all.
if (err) {
return handleError(res, err);
}
if (!post) {
return res.status(404).send('Post not found');
}
Comment.create(req.body, function (err, comment) {
if (err) {
return handleError(res, err);
}
post.comments.push(comment.id);
post.save(function (err) {
if (err) return handleError(res, err);
return res.status(201).json(comment);
});
});
});
};
route.js
app.use('/api/providers/:providerId/posts/:postId/comments', require('./api/provider/post/comment'));
index.js
var controller = require('./comment.controller.js');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.update);
router.patch('/:id', controller.update);
router.delete('/:id', controller.destroy);
router.put('/:id/upvote', controller.upvote);
in client side:
factory:
//create new comment for post
ob.createComment = function(providerId, postId,comment) {
console.log('i am inside factory');
return $http.post('/api/providers/'+ providerId + '/posts/' + postId + '/comments' ,comment, {
headers: {Authorization: 'Bearer '+Auth.getToken()}
}).success(function(data){
_.forEach(ob.provider.posts,function(value,index){
if(value._id === post._id){
ob.posts[index].comments.push(data);
}
})
ob.current.comments.push(data)
// ob.provider1._id.posts.push(data);
});
};
in my controller
$scope.addComment = function(){
// if(!$scope.title || $scope.title === '') { return; }
if(!$scope.body || $scope.body === '') { return; }
console.log('$stateParams',$stateParams);
providers.createComment($stateParams.providerId, $stateParams.postId,{
//title: $scope.title,
body: $scope.body
});
$scope.body = '';
$scope.title = '';
};
This is my model in whole the project.