Getting "Error Authenticator must be set" when call AuthorizationV1 to obtain speech-to-text token - ibm-watson

Running Node v10
ibm-watson v5.1.0
Getting error when try to obtain token for speech-to-text.
#
{
"message": "Authenticator must be set.",
"name": "Error",
"stack": "Error: Authenticator must be set.\n at AuthorizationV1.BaseService (/nodejsAction/VuncPM95/node_modules/ibm-cloud-sdk-core/lib/base-service.js:66:19)\n at new AuthorizationV1 (/nodejsAction/VuncPM95/node_modules/ibm-watson/authorization/v1.js:44:28)\n at Object.token (/nodejsAction/VuncPM95/services/stt.js:17:32)\n at speech-to-text_token (/nodejsAction/VuncPM95/index.js:42:54)\n at Object.exec (/nodejsAction/VuncPM95/index.js:33:73)\n at Promise (/nodejsAction/VuncPM95/index.js:10:16)\n at new Promise ()\n at NodeActionRunner.main [as userScriptMain] (/nodejsAction/VuncPM95/index.js:9:12)\n at Promise (/nodejsAction/runner.js:73:35)\n at new Promise ()"
}
#
When try with
typescript 3.6.4
#
{
"message": "Authenticator must be set.",
"name": "Error",
"stack": "Error: Authenticator must be set.\n at t.e (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:45665)\n at new t (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :16:49145)\n at Object.token (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:44594)\n at speech-to-text_token (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43617)\n at Object.exec (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43498)\n at Promise (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43038)\n at new Promise ()\n at NodeActionRunner.a [as userScriptMain] (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43016)\n at Promise (/nodejsAction/runner.js:73:35)\n at new Promise ()"
}
#
export const SpeechToText = {
token: (params: WatsonParams) => {
const sttCredentials = Object.assign(
{
username: params.speechToTextUsername, // or hard-code credentials here
password: params.speechToTextPassword,
iam_apikey: params.speechToTextIamApikey, // if using an RC service
url: params.speechToTextUrl ? params.speechToTextUrl : SpeechToTextV1.URL
},
vcapServices.getCredentials('speech_to_text') // pulls credentials from environment in bluemix, otherwise returns {}
);
const sttAuthService = new AuthorizationV1(sttCredentials);
return Observable.create((observer) => {
sttAuthService.getToken(function(err, response) {
if (err) {
console.log('Error retrieving token: ', err);
observer.error('Error retrieving token...');
} else {
const token = response.token || response;
if (params.speechToTextIamApikey) {
observer.next({ accessToken: token, url: sttCredentials.url });
} else {
observer.next({ token: token, url: sttCredentials.url });
}
observer.complete();
}
});
});
}
}
Expect it to return a token.

Authentication changed in v5. See MIGRATION-V5
The SDK service constructors now accept Authenticator objects that are used to authenticate requests. The constructors no longer accept individual credentials like username and password.
Here's an example from the API reference.
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const speechToText = new SpeechToTextV1({
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
url: '{url}',
});

Related

Cannot update or save data on second or next user in mongodb

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

Meteor call inside cursor.map throws error

I have a meteor call "Send to all" inside another meteor call and cursor.map which throws error on server side but runs fine on client side below is the error: how do i remove this error ? meteor 1.8 react 16.8
send all numbers error2 { Error: Method 'Send to all' not found [404]
I20190720-13:08:56.527(5.5)? at Server.applyAsync (packages/ddp-server/livedata_server.js:1648:9)
I20190720-13:08:56.528(5.5)? at Server.apply (packages/ddp-server/livedata_server.js:1625:26)
I20190720-13:08:56.529(5.5)? at Server.call (packages/ddp-server/livedata_server.js:1607:17)
I20190720-13:08:56.530(5.5)? at Find all numbers.userKisandb.find.fetch.map.Mob (imports/api/userKisan.js:47:24)
I20190720-13:08:56.531(5.5)? at Array.map (<anonymous>)
I20190720-13:08:56.531(5.5)? at MethodInvocation.Find all numbers (imports/api/userKisan.js:44:21)
I20190720-13:08:56.532(5.5)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1771:12)
I20190720-13:08:56.533(5.5)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190720-13:08:56.533(5.5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20190720-13:08:56.534(5.5)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190720-13:08:56.536(5.5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20190720-13:08:56.537(5.5)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190720-13:08:56.539(5.5)? at new Promise (<anonymous>)
I20190720-13:08:56.539(5.5)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190720-13:08:56.540(5.5)? at packages/ddp-server/livedata_server.js:559:43
I20190720-13:08:56.541(5.5)? isClientSafe: true,
I20190720-13:08:56.542(5.5)? error: 404,
I20190720-13:08:56.542(5.5)? reason: 'Method \'Send to all\' not found',
I20190720-13:08:56.544(5.5)? details: undefined,
I20190720-13:08:56.544(5.5)? message: 'Method \'Send to all\' not found [404]',
I20190720-13:08:56.545(5.5)? errorType: 'Meteor.Error' }
'Find all numbers' (smsText) {
if(!this.userId) {
throw new Meteor.Error('not-authorized');
}
return userKisandb.find({
userId: this.userId
}).fetch().map((Mob) => {
// return Mob.Mnumber
if(Mob.Mnumber) {
Meteor.call('Send to all',Mob.Mnumber,smsText,(err,resp) => {
//this call throws error on server side
//sms.js
if(err){
console.log("send all numbers error2", err);
} else {
console.log("send all numbers sucess", resp);
}
})
}
});
},
And Method is
Meteor.methods({
'Send to all'(mob,text) {
let from = 1234;
console.log(from);
},
})

How to write to google finance API?

I know how to read from the google finance api, it is pretty simple.
But when I try to write I get the following error:
Error: Request had insufficient authentication scopes
This is my code:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('./GoogleFinanceApi/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), appendData);
});
Here ^ in the append data is where I am calling the function, it works when i do the listMajors but not when I do the appendData...
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}
function appendData(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.append({
auth: auth,
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}
What am I doing wrong? I have read some posts and they say they didn't add the resource so I tried to fix that but still nothing works...
Probably the issue is in google.sheets in appendData. Perhaps you need to pass auth to google.sheets before you access sheets as how you are doing in listMajors but you are passing auth to the sheets instead of google.sheets. This might be an issue
Can you try below updated code
function appendData(auth) {
const sheets = google.sheets({version: 'v4', auth})
sheets.spreadsheets.values.append({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}

web3.js Error: Couldn't decode uint8 from ABI: 0x

env: mac node web3
I am trying to use a smart contract instance for a deployed contract in node.js. I am getting the error below and don't know how to solve it.
code:
app.js
web3.eth.getBlock(0, function (error, result) {
if (!error) {
web3.eth.personal.newAccount("test", function (error, result) {
if (!error) {
console.log("new account:", result);
//init contract
var smartToken = new web3.eth.Contract(config.smartTokenAbi, config.smartTokenAddr, {
from: result,
gasPrice: '20000000000'
});
var privateSale = new web3.eth.Contract(config.privateSaleAbi, config.privateSaleAddr, {
from: result,
gasPrice: '20000000000'
});
privateSale.methods.state().call({}, function (error, result) {
console.log("------", error, result);
});
} else {
console.log(error)
}
});
console.log("Connect to " + config.host + ' success');
} else {
console.log("Can't connect to " + config.host);
throw error;
}
});
output:
new account: 0x7051ebDe6A252858A3E5b06Dc7608677B18EC093
------ Error: Couldn't decode uint8 from ABI: 0x
at SolidityTypeUInt.formatOutputUInt [as _outputFormatter] (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/formatters.js:174:15)
at SolidityTypeUInt.SolidityType.decode (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/type.js:252:17)
at /Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/index.js:327:49
at Array.forEach (<anonymous>)
at ABICoder.decodeParameters (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/index.js:326:13)
at Contract._decodeMethodReturn (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-contract#1.0.0-beta.34#web3-eth-contract/src/index.js:459:22)
at Method.outputFormatter (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-contract#1.0.0-beta.34#web3-eth-contract/src/index.js:812:46)
at Method.formatOutput (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-method#1.0.0-beta.34#web3-core-method/src/index.js:163:54)
at sendTxCallback (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-method#1.0.0-beta.34#web3-core-method/src/index.js:475:33)
at /Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-requestmanager#1.0.0-beta.34#web3-core-requestmanager/src/index.js:147:9
at XMLHttpRequest.request.onreadystatechange (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-providers-http#1.0.0-beta.34#web3-providers-http/src/index.js:77:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) undefined

apollo-fetch ends up in network error for a simple garphql query

I am using apollo-fetch to fetch a graphql data.
I am ending up in a script error and the request does not go through. I an not sure what is going wrong in a fairly simple request like this. Please help.
Here's the error:
Uncaught (in promise) Error: Network request failed to return valid JSON
at throwHttpError (apollo-fetch.js:41)
at apollo-fetch.js:141
at <anonymous>
throwHttpError # apollo-fetch.js:41
(anonymous) # apollo-fetch.js:141
Promise rejected (async)
Here's the code:
const { createApolloFetch } = require('apollo-fetch');
PlayService.prototype.getPlays = function(playID) {
const fetch = createApolloFetch({
uri: 'graphql'
});
const playQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
fetch({
query: playQuery,
variables: { playid: playID }
}).then((res) => {
console.log(res.data);
});
};
My best guess is that is that your uri value is incorrect. You should provide a fully qualified uri like this
PlayService.prototype.getPlays = function(playID) {
const fetch = createApolloFetch({
uri: 'http://localhost:3000/graphql'
});

Resources