Meteor call inside cursor.map throws error - reactjs

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);
},
})

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

Mongoose Validation Error (in Express) returning HTML page instead of JSON response

I want to fetch the error message that is returned by Mongoose, but the response I'm getting is in the form of an HTML page.
I'm using the following route handler to make a POST request:
app.post('/api/persons', (req, res, next) => {
if(!req.body.name) {
return res.status(404).json({
error: "Name missing."
})
}
else if(!req.body.number) {
return res.status(404).json({
error: "Number missing."
})
}
else {
const person = new Person({
name: req.body.name,
number: req.body.number
})
person.save().then(savedPerson => {
res.json(savedPerson)
})
.catch(error => next(error))
}
})
and the following Error Handler function:
const errorHandler = (error, req, res, next) => {
console.error(error.message);
if(error.name === 'CastError') {
return res.status(400).send({ error: 'Malformated entry' })
}
else if(error.name === 'ValidationError') {
return res.status(400).json({ error: 'Name must be at least 3 characters long.' })
}
next(error)
}
app.use(errorHandler)
The errorHandler is the last middleware to be called.
On the frontend, I'm using this to extract the error message and display it on the screen.
recordService.create(temp).then(response => {
setPersons(persons.concat(response));
setNewName("");
setNewNumber("");
setPersonsToShow(persons.concat(response));
setErrorMessage(`${temp.name} has been added!`)
setTimeout(()=>{
setErrorMessage(null)
}, 3000)
}).catch(error => {
console.log(error.response.data);
setErrorMessage(error.response.data);
setTimeout(()=>{
setErrorMessage(null)
}, 3000)
resordService is a module that returns axios route handler functions and create is an alias for POST.
When I display the error.response.data, I'm getting the following response:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>ValidationError: Person validation failed: name: Path `name` (`er`) is shorter than the minimum allowed length (3)., number: Validator failed for path `number` with value `3412`<br> at model.Document.invalidate (D:\Code\WebDev\Full Stack Open\Exercises\part3\node_modules\mongoose\lib\document.js:2948:32)<br> at D:\Code\WebDev\Full Stack Open\Exercises\part3\node_modules\mongoose\lib\document.js:2737:17<br> at D:\Code\WebDev\Full Stack Open\Exercises\part3\node_modules\mongoose\lib\schematype.js:1324:9<br> at processTicksAndRejections (node:internal/process/task_queues:78:11)</pre>
</body>
</html>
I'm only interested in the Person validation failed: name: Path name (er) is shorter than the minimum allowed length (3)., number: Validator failed for path number with value 3412 part.
How can I get the response as a JSON object?

Upgrading react-script creates error "no elements in sequence"

I upgraded react-scripts to 4.0.3.
My react test now results in a error of message: 'no elements in sequence', name: 'EmptyError'. Seems to point towards the below code as the issue:
receiver$
.pipe(
filter(message => message.requestId === requestId),
first()
)
.subscribe(
({ success, data, error }) => {
if (success) {
// console.log(`data for - ${serverCommand}`, data);
resolve(data);
} else {
console.log('rejecting this got data ', data, error);
reject(error || data);
}
},
error => console.warn('Caught error in make request', error)
);
});
i have tried replacing first()x with take(1) but still no luck. Can anyone help?

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

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}',
});

Balanced-Payments Try Catch response

I've attempting to learn how to set up credit card payments and using a Balanced Payments test marketplace. I haven't ever set up a try catch statement before and I am having some trouble with processing the response.
Here is my controller try/catch statement:
try{
$card->debits->create(array(
"amount" => $amount,
"appears_on_statement_as" => "test",
"description" => $invoiceId,
"order" => $order,
));
} catch (Balanced\Errors\Declined $e) {
$this->arrResponse['status'] = $e->getMessage();
return Response::json($this->arrResponse);
}
$invoice->save();
// send email function...
//redirect
$this->arrResponse['status'] = SUCCESS;
return Response::json($this->arrResponse);
I can see the error on chrome developer tools, but I can't make it appear on my view.
Chrome dev tools 500 internal server error statement:
error: {type: "Balanced\Errors\Declined", message: "",…}
file: "/Applications/MAMP/htdocs/testcc/vendor/balanced/balanced/src/Balanced/Errors/Error.php"
line: 42
message: ""
type: "Balanced\Errors\Declined
processpayment.js file:
jQuery.post(baseURL+'/processPayment', {
uri: fundingInstrument.href,
amount: amount,
invoiceId: invoiceId,
}, function(r) {
// backend response
if (r.status === 200) {
$('#msgSection').empty().removeClass('alert-error alert-success').addClass('alert-success').text(' payment has been received').show();
} else {
// failure from backend
$('#msgSection').empty().removeClass('alert-success').addClass('alert-warning').text('error').show();
}
});
When test card is processed successfully, everything works and success message appears on my view. However, when I use a test card that is declined, no message is sent to my view. Anyone see what I am doing wrong?
try to check balanced-php client testsuite to see how they use try catch block from here
so your code would be like.
try{
$card->debits->create(array(
"amount" => $amount,
"appears_on_statement_as" => "test",
"description" => $invoiceId,
"order" => $order,
));
} catch (Balanced\Errors\Declined $e) {
$this->arrResponse['status'] = $e->category_code;
return Response::json($this->arrResponse);
}
$invoice->save();
// send email function...
//redirect
$this->arrResponse['status'] = SUCCESS;
return Response::json($this->arrResponse);
$e->category_code will be either funding-destination-declined or authorization-failed or card-declined

Resources