Create Spreadsheet for read and write using Node js - node.js

I Need to create a spreadsheet like a google sheet with user authentication. I have stuck with how to start this project because I couldn't find which NPM module needs to use.
so Kindly help anyone push me in the right direction?

I've been working on similar task few weeks ago.
So here is the mini help for you.
1. Read and follow Node.js Quickstart guide.
Keep an eye on the next concepts like:
Scopes
For example to get a value from a cell we can use spreadsheets.values.get
Scopes for this method are (use 1 of these):
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/spreadsheets.readonly
in node.js it can be an array
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
Token
Once you run for the first time your index.js file the Terminal will ask you for authorization, on finish you will find a token.json in your work directory.
If you change Scopes -> delete token.json from your directory
SpreadsheetId
When you create/edit your spreadsheet you get similar url
https://docs.google.com/spreadsheets/d/1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw/edit#gid=0
1eqRe0ksSwgOoPO0C_mZE6opjS1TlsCU5g1HtkiiILuw is the ID
2. Create custom functions using Google Sheets API Reference
Example how to get cell values:
const sheets = google.sheets({ version: 'v4', auth });
function getCellsValue(cells, callback){
sheets.spreadsheets.values.get({
spreadsheetId: 'spreadsheetId',
range: cells
}, (err, res) => {
if (err) return console.log('Error #1001 : getCellsValue: ' + err);
const output = res.data.values;
if (output.length) {
callback(output);
return output;
} else {
console.log('No data found.');
}
});
}
// here is the example use of this function which output values from D2:D13
getCellsValue("D2:D13", (e) => {
for(let i = 0; i < e.length; i++){
console.log(e[i].toString());
}
}, (err, res) => {
if (err) return console.error('The API returned an error: ', err.message);
})
3. Make a use of Try this API
This is very useful tool.
In case you need more help just use Stackoverflow for more transparency.
Stackoverflow helps you when you make a very detailed question.
I hope this helped you and you can start your Google Sheets API journey.

Related

Is it possible to duplicate a specific slide using google slide api?

Google Slides Api (Node JS / JavaScript) - is it possible to create a duplicate of a specific slide like for example assuming slide no 5 needs to be duplicated 3 times?
I believe your goal and your current situation as follows.
You want to copy the specific slide in Google Slides several times.
In your question, you want to copy No. 5 slide 3 times.
You want to achieve this using googleapis for Node.js.
You have already been able to get and put values for Google Slides using Slides API.
In this case, I thought that the method of batchUpdate in Slides API can be used.
Sample script:
In this sample script, please use auth retrieved from your script. If you want to see the script for authorizing for Node.js, you can see Quickstart for Node.js. Ref In this case, please use the scope of https://www.googleapis.com/auth/presentations.
const presentationId = "###"; // Please set the presentation ID (Google Slides ID).
const pageNumber = 5; // Please set the page number. In your question, it's 5.
const numberOfCopy = 3; // Please set the number of copy. In your question, it's 3.
const slides = google.slides({ version: "v1", auth: auth });
slides.presentations.get(
{
presentationId: presentationId,
fields: "slides(objectId)",
},
(err, res) => {
if (err) {
console.log(err);
return;
}
const pageObjectId = res.data.slides[pageNumber - 1].objectId;
const requests = [];
for (let i = 0; i < numberOfCopy; i++) {
requests.push({ duplicateObject: { objectId: pageObjectId } });
}
slides.presentations.batchUpdate(
{
presentationId: presentationId,
resource: { requests: requests },
},
(err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.data);
}
);
}
);
When above script is run, the page object ID of No. 5 slide is retrieved from the Google Slides using the get method, and create the request body for copying 3 times and request it using the batchUpdate method.
Note:
In this sample script, it supposes that auth retrieved from your authorization script can be used. Please be careful this.
References:
Method: presentations.get
Method: presentations.batchUpdate
DuplicateObjectRequest

using node.js to query a google sheet and return row

So I am building a discord bot which is using google sheets like a database. I would like the user to be able to enter a command with a unique ID which every row will have and then return all the values of said row and store than as a variable. which will then later be used elsewhere.
The command the user would run is ">Read (UNIQUEID)", then I would like the bot to reply with, "(UNIQUEID) has been found" if it is found and "(UNIQUEID) can not be found".
The user would then use the second command ">Upload" to essentially upload that entire row to a new spreadsheet.
I am confident I can finish the >Upload code by myself, but for the life of me I dont know how to query using the google sheets api. for some reference below I have attached an image of my sheet I want to read from.
Google Sheet To Read From
There would also be a lot more information in the google sheet, but for testing purposes I left it with only one entry.
Edit 1: I have been looking into the Google Visualization API, I did a bit of research but Im not sure this would actually work with sheets? From some of the documentation it seems like its for charts..
I found the answer to my issue from another stackoverflow question which was also answered by #Tanaike. Below is the code.
const request = require("request");
const csvParse = require("csv-parse");
const spreadsheetId = "DOCUMENT_ID"; // Document ID
const sheetId = "SHEET_ID"; // sheet ID
const searchId = `${QUERY}`; // what im searching for
spread.getRequestHeaders().then((authorization) => {
const query = `select * where K='${searchId}'`; // K can be changed to the col the data is on
const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:csv&gid=${sheetId}&tq=${encodeURI(query)}`;
let options = {
url: url,
method: "GET",
headers: authorization,
};
request(options, (err, res, result) => {
if (err) {
console.log(err);
return;
}
if (result === ("")) {
return message.channel.send(`\`${QUERY}\` Did not match to any records.`); //ID didnt match
} else {
message.channel.send(`\`${QUERY}\` has been matched with; ${result}`) //confirms ID has matched
csvParse(result, {}, (err, ar) => console.log(ar)) // console logs results
````

Get result in from YouTube channel in nodejs

I am using youtube-node npm to find out all the video list. The documentation is on the link https://www.npmjs.com/package/youtube-node.
But I want that my search only show result of a specific channel i.e if I search hello, then it only give result of AdeleVEVO YouTube channel.
I cant find suitable documentation for that. I don't want to use oauth credentials, I only want to use youtube-node npm.
In package doc you have a sample search, make sure you include in the params parameter an object with the values you want, in your case see in youtube api doc that you need to specify the channelId. Try this way:
var YouTube = require('youtube-node');
var youTube = new YouTube();
youTube.setKey('AIzaSyB1OOSpTREs85WUMvIgJvLTZKye4BVsoFU');
youTube.search('World War z Trailer', 2, {channelId: <string value of the channelId>}, function(error, result) {
if (error) {
console.log(error);
}
else {
console.log(JSON.stringify(result, null, 2));
}
})
;
If you are the owner of the channel, you can use the forMine parameter of the YouTube API for this. Setting this parameter will limit the search to the authorized user's videos. Below is a sample from the official documentation.
IMPORTANT NOTE: Do not use the youtube-node module for this, specifically because--in my experience at least--the addParam() function does not reliably add parameters to the request (e.g., in my code I called youtube_node.addParam('safeSearch', 'strict');, but restricted videos would still be returned in the results.)
Instead, use the YouTube Data API directly as shown in this quickstart example.
// Sample nodejs code for search.list
function searchListMine(auth, requestData) {
var service = google.youtube('v3');
var parameters = removeEmptyParameters(requestData['params']);
parameters['auth'] = auth;
service.search.list(parameters, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
}
//See full code sample for authorize() function code.
authorize(JSON.parse(content), {'params': {'maxResults': '25',
'forMine': 'true',
'part': 'snippet',
'q': 'fun',
'type': 'video'}}, searchListMine);

How to know which data has been updated recently in google sheet using API v4

I am using node js google drive meta data readonly and spreadsheet scope for reading data with google API v4. But how to get last updated rows , columns and data that has been updated in a sheet ?
****Update**
var fetchChanges = function(pageToken,pageFn, callback) {
service.changes.list({
auth:oauth2Client,
pageToken: pageToken,
fields: 'kind,nextPageToken,newStartPageToken,changes(kind,type,time,removed,fileId,file,teamDriveId,teamDrive)'
}, function (err, res) {
if (err) {
console.log("------err in service.changes : " ,err);
return;
} else {
console.log("change resp : ", res.changes);
// Process changes
res.changes.forEach(function (change) {
console.log("Change found for file: ", change.fileId);
});
if (res.newStartPageToken) {
// Last page, save this token for the next polling interval
callback(null, res.newStartPageToken);
// console.log("--------newStartPageToken : ",res.newStartPageToken);
}
if (res.nextPageToken) {
pageFn(res.nextPageToken, pageFn, callback);
}
}
});
};
Response I am getting in console as well as in google explorer:
{ kind: 'drive#changeList',
newStartPageToken: '7911',
changes: [] }
}
Note changes object data not present and nextPageToken also absent.
I got the solution :
I have to get the future changes token at first then using that token changes done after the token creation. And remember to add the space as parameters like this:
spaces(drive,appDataFolder,photos)
There is currently no API you could use to directly retrieve the data from the last edit in a Spreadsheet.
As a workaround, you could implement an App Script that detects changes in the Spreadsheet, stores the data you need temporarily (to a different sheet), and then access it from there.
Also see these posts:
https://webapps.stackexchange.com/q/33372/154267
https://webapps.stackexchange.com/q/31894/154267
Automatic timestamp when a cell is filled out

Azure mobile apps CRUD operations on SQL table (node.js backend)

This is my first post here so please don't get mad if my formatting is a bit off ;-)
I'm trying to develop a backend solution using Azure mobile apps and node.js for server side scripts. It is a steep curve as I am new to javaScript and node.js coming from the embedded world. What I have made is a custom API that can add users to a MSSQL table, which is working fine using the tables object. However, I also need to be able to delete users from the same table. My code for adding a user is:
var userTable = req.azureMobile.tables('MyfUserInfo');
item.id = uuid.v4();
userTable.insert(item).then( function (){
console.log("inserted data");
res.status(200).send(item);
});
It works. The Azure node.js documentation is really not in good shape and I keep searching for good example on how to do simple things. Pretty annoying and time consuming.
The SDK documentation on delete operations says it works the same way as read, but that is not true. Or I am dumb as a wet door. My code for deleting looks like this - it results in exception
query = queries.create('MyfUserInfo')
.where({ id: results[i].id });
userTable.delete(query).then( function(delet){
console.log("deleted id ", delet);
});
I have also tried this and no success either
userTable.where({ id: item.id }).read()
.then( function(results) {
if (results.length > 0)
{
for (var i = 0; i < results.length; i++)
{
userTable.delete(results[i].id);
});
}
}
Can somebody please point me in the right direction on the correct syntax for this and explain why it has to be so difficult doing basic stuff here ;-) It seems like there are many ways of doing the exact same thing, which really confuses me.
Thanks alot
Martin
You could issue SQL in your api
var api = {
get: (request, response, next) => {
var query = {
sql: 'UPDATE TodoItem SET complete=#completed',
parameters: [
{ name: 'completed', value: request.params.completed }
]
};
request.azureMobile.data.execute(query)
.then(function (results) {
response.json(results);
});
}};
module.exports = api;
That is from their sample on GitHub
Here is the full list of samples to take a look at
Why are you doing a custom API for a table? Just define the table within the tables directory and add any custom authorization / authentication.

Resources