const projectId = 'natural-nebula-number';
const {
Translate
} = require('#google-cloud/translate').v2;
const translate = new Translate({
projectId,
});
async function quickStart() {
const text = 'Hello, world!';
const target = 'ru';
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
quickStart();
I wrote some code for using google translate api with node.js
i had install #google-cloud/translate. through npm.
and i did copy,paste code in this site google api usage
but i got some error on my command
here is the error message.
(node:440) UnhandledPromiseRejectionWarning: Error: The request is missing a valid API key.
at new ApiError (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:73:15)
at Util.parseHttpRespBody (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:208:38)
at Util.handleResp (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:149:117)
at /mnt/c/Users/U suk jang/Desktop/testinf/node_modules/#google-cloud/common/build/src/util.js:477:22
at onResponse (/mnt/c/Users/U suk jang/Desktop/testinf/node_modules/retry-request/index.js:228:7)
at /mnt/c/Users/U suk jang/Desktop/testinf/node_modules/teeny-request/build/src/index.js:226:13
i wrote actually full projectid (of couse real number).
but they say they cannot find my api key.
how should i give my api key to google
and where is the google-docs for this problem?
You copy-pasted the code in the link provided, but did you read the article and follow all prerequisite steps? It links to another article, Cloud Translation: NodeJS Client. There you will find that you need to pay special attention top step 4 (authentication) mentioned under the Quickstart paragraph. Without it, the used client library will not find your API key.
Related
I am using the Xero-node SDK to automatically create client invoices which works well.
At the end of the process, I would like to automatically email the client the invoice.
In the documentation it has the following example:
const xeroTenantId = 'YOUR_XERO_TENANT_ID';
const invoiceID = '00000000-0000-0000-0000-000000000000';
const requestEmpty: RequestEmpty = { };
try {
const response = await xero.accountingApi.emailInvoice(xeroTenantId, invoiceID, requestEmpty);
console.log(response.body || response.response.statusCode)
} catch (err) {
const error = JSON.stringify(err.response.body, null, 2)
console.log(`Status Code: ${err.response.statusCode} => ${error}`);
}
I have 2 questions:
The requestEmpty method does not work in javascript. Does anyone know the correct structure of requestEmpty?
I have used requestEmpty = { } but this throws an error => even though the system does actually send an email (probably a bug)
AND....
Is there a way for me to specify the email template that I would like the invoice to use (if I have specific templates setup in the web version)? Currently it seems to use the default Xero email template.
If you don't get an answer to your first query here, please can you raise it on the SDK page in Github and the Xero SDK team will look into this for you.
With regards to point 2, it is not possible to choose the email template when sending through the API, a basic template is used.
So after I have written a good part of my app, I am now becoming maximally confused regarding the use of the admin sdk in cloud functions regarding firestore.
I only want to query, read and write data from the cloud function environment correctly. Which documentation do I have to use, how do I correctly initialize the "Admin SDK" and implement the corresponding methods and functions?
It seems like I have mixed up v9 and v10 and even by reading the docs I still can't find a red thread, on how to use it correctly.
I am currently importing and initializing like that.
const functions = require("firebase-functions");
const { initializeApp } = require("firebase-admin/app");
const admin = require("firebase-admin");
const app = initializeApp();
when I initialize like that, and would like to work with firestore. There are different options which I do not understand - for example.
const userRef = admin.firestore().collection("users").doc(data.userID);
enables me to access "collection"
However when using
const userRef = admin.firestore
I am only able to choose admin.firestore.CollectionGroup and admin.firestore.CollectionReference, which are classes? What is up with that?
Furthermore this approach seems to be outdated as this site of the docs (which I only recently came to know), says that I should use a modular approach, as I would on the client side, with.
import { getFirestore } from 'firebase-admin/firestore'
getFirestore();
So far so good. Now when I take a look at the docs, I am led to this page. The question I ask myself there are, what are External Api Re-Exports? By clicking on any of the referenced functions I get redirected to this, which contains the reference for the nodejs client and also subgroups called firestore admin client, as well as FirestoreAdmin. Neither of those subgroups contain anything which has something to do with querying a collection. There is a section about collections and querying which displays examples of asynchronous programming with .then, but from what I heard it is generally more beneficial to use async/await?
In addition to that the quickstart guide, recommends an initialization like this.
const {Firestore} = require('#google-cloud/firestore');
// Create a new client
const firestore = new Firestore();
Furthermore the firebase docs, seem to have a dedicated documentation on how to use the Admin SDK, with the realtime database here but not how to use it with firestore?
I am just so confused, as to which documentation to use, and I couldn't find any examples how to do standard operations. I guess I also lack fundamental understanding about the Admin SDK itself and its integration in firebase.
The code I have written now is working, however I think it is not "right" from a documentation point of view.
exports.createUserDoc = functions.auth.user().onCreate((user) => {
const userRef = admin.firestore().collection("users").doc(user.uid);
const userData = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
tokens: 0,
};
return userRef.set(userData);
});
exports.setWriteTimestamp = functions.https.onCall((data, context) => {
//in the if check below, retrieve the corresponding pool document and check whether the "open" field is true
const poolRef = admin.firestore().collection("pools").doc(data.slug);
const poolDoc = poolRef.get().then((doc) => {
if (doc.exists && doc.data().open) {
return poolRef.update({
writeTimestamp: admin.firestore.FieldValue.serverTimestamp(),
});
} else {
return null;
}
});
});
Thank you for your help.
From a node.js application (a discord bot)
I try to acess to a public googlesheet using the npm package google-spreadsheet
I followed each step carefully, but I would like to use only the API key authentification method instead of a more risky Oauth identification
(my discord bot is public, on heroku and I don't want to mess around with too much sensitive information even though i use environment variables)
On the documentation of google-spreadsheet.js it mentions that :
// OR use API key -- only for read-only access to public sheets
doc.useApiKey('YOUR-API-KEY');
I sucessfully could connect to the
spreadsheet
and read the title of it and get the titles of each sheet but when I call
await sheet.loadCells();
it gives me the following error
Google API error - [401]
Request is missing required authentication credential.
Expected OAuth 2 access token,
login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.
What would be the right way or READING ONLY cells, if possible using only the API KEY authentification ?
here is my full code :
const sheetId = "1Bny-ZsCG_oUuS0nTbR-7tBBZu47_ncS9qGYaMpuprWU"
var loaded = {}
if (message) {
message.reply("je me connecte à Google Sheets...")
}
const doc = new GoogleSpreadsheet(sheetId);
doc.useApiKey(process.env.GOOGLE_API_KEY);
await doc.loadInfo();
loaded.docTitle = doc.title;
loaded.sheets = {};
if (message) {
message.reply("...connection réussie, je récupère les infos...")
}
// get the spreadsheets
for (let s = 0; s < doc.sheetCount; ++s ) {
const sheet = doc.sheetsByIndex[s];
loaded.sheets[sheet.title] = {sheetReference:sheet};
loaded.sheets[sheet.title].data = []
await sheet.loadCells(); // <---------it seems to block here
for (let row= 0; row < sheet.rowCount; ++row) {
loaded.sheets[sheet.title].data.push([])
for (let col = 0; col < sheet.columnCount; ++col) {
let cell = sheet.getCell(row, col).value;
loaded.sheets[sheet.title].data[row].push(cell)
}
}
Thank you very much !
You want to retrieve the values from Google Spreadsheet using the API key.
The Google Spreadsheet is publicly shared.
You want to achieve this using google-spreadsheet.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
When I saw the source script of google-spreadsheet, it seems that sheet.loadCells() requests with the POST method using the API key. Ref Unfortunately, the API key cannot use the POST method. So such error occurred. I think that the reason of this issue is due to this. For example, when the access token from OAuth2 and service account is used, I could confirm that sheet.loadCells() worked. From this situation, this might be a bug or the specification of the library.
Fortunately, the values can be retrieved from the publicly shared Google Spreadsheet with the API key. So as one of several workarounds, in this answer, googleapis for Node.js is used as a simple method. This is the official library.
Sample script:
At first, please install googleapis. And please set the variables of spreadsheetId and APIKey.
const { google } = require("googleapis");
const spreadsheetId = "1Bny-ZsCG_oUuS0nTbR-7tBBZu47_ncS9qGYaMpuprWU"; // This is from your script.
const APIKey = "### your API key ###";
const sheets = google.sheets({version: "v4", auth: APIKey});
sheets.spreadsheets.get({ spreadsheetId: spreadsheetId }, (err, res) => {
if (err) {
console.error(err);
return;
}
sheets.spreadsheets.values.batchGet(
{
spreadsheetId: spreadsheetId,
ranges: res.data.sheets.map(e => e.properties.title)
},
(err, res) => {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(res.data));
}
);
});
When you run the script, the all values from all sheets in the publicly shared Spreadsheet are retrieved.
In above sample script, there are 2 methods of spreadsheets.get and spreadsheets.values.batchGet were used.
References:
google-api-nodejs-client
Method: spreadsheets.get
Method: spreadsheets.values.batchGet
If I misunderstood your question and this was not the direction you want, I apologize.
Author of google-spreadsheet here.
I've just released an update that should fix this problem. It was a very subtle difference in google's API docs that I missed. The loadCells method now will default to the regular get endpoint if using an API key only. The interface for loadCells is the same, but will only support A1 ranges in this mode.
Cheers!
This flow is confusing me a bit and I would appreciate any help/diagram/flow-chart that could help me understand this better:
As an example, I would like to access Google's API. The thing is what I want to access sits on an enterprise account and to even get to use any of Google Suite Applications, I have to log in to my work account (SSO.) On top of that, all this needs to be done via VPN.
I've used Puppeteer for this in Node.js, and though it works on my machine, It stops working if I try to host it anywhere else because (I assume) due to the VPN issue. It's clunky and just plain hack-ish because I'm just automating what I normally do on the browser.
What are the best practices in being able to use Google's API? What does the algorithm look like?
you can use the 'googleapis' package on npm
https://www.npmjs.com/package/googleapis
here is an example...
const {google} = require('googleapis');
const bigquery = google.bigquery('v2');
async function main() {
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const authClient = await auth.getClient();
const projectId = await auth.getProjectId();
const request = {
projectId,
datasetId: '<YOUR_DATASET_ID>',
// This is a "request-level" option
auth: authClient
};
const res = await bigquery.datasets.delete(request);
console.log(res.data);
}
main().catch(console.error);
you can use a proxy by setting the process.env.http or process.env.httpsenvironment variables to solve your vpn issue
I am trying to deploy my simple solidity smart contract onto the Rinkeby Network but I keep getting the error:
UnhandledPromiseRejectionWarning: Error: The contract code couldn't be
stored, please check your gas limit.
My solidity code is simple
pragma solidity ^0.4.18;
contract Greetings{
string public message;
function Greetings(string initialMessage) public{
message = initialMessage;
}
function setMessage(string newMessage) public {
message = newMessage;
}
}
and my deploy script is:
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface,bytecode} = require('./compile');
const provider = new HDWalletProvider(
'twelve word mnemonic...',
'https://rinkeby.infura.io/GLm6McXWuaih4gqq8nTY'
);
const web3 = new Web3(provider);
const deploy = async () => {
accounts = await web3.eth.getAccounts();
console.log('attempting to deploy from account',accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({data:bytecode, arguments:['Hello World']})
.send({from: accounts[0], gas:'1000000'});
console.log('Contract deployed to', result.options.address);
};
deploy();
Funny thing is, I used to be able to deploy successfully, but when i created a new project and re did the same code, i get this error now. Please help!
Had exactly same problem! Seems it is caused by the bug in the "truffle-hdwallet-provider" version 0.0.5. During the udemy course it was using "0.0.3" apparently.
If you do the following should be okay, it worked for me.
npm uninstall truffle-hdwallet-provider
npm install --save truffle-hdwallet-provider#0.0.3
Then I ran the same contract which has deployed successfully.
Good luck!
This issue can be solved by adding the '0x' as the prefix of the bytecode:
.deploy({ data: '0x' + bytecode, arguments: ['Hi there!'] })
More information is at https://ethereum.stackexchange.com/a/47654.
I believe bytecode is being treated as a single number rather than a series of bytes. Instead of submitting data:bytecode, try:
data:'0x0' + bytecode
it will "preserve" bytecode value as a string
Also just remove the gas field let metamask decide the gas limit. this way works for me.