I'm developing an ecommecer and I'm using braintree as a payment method, some time ago there was no problem with this. but now it sometimes works without problems and there are times when I get this error in the backend: ReferenceError: error is not defined
exports.processPayment = (req, res) => {
let nonceFromTheClient = req.body.paymentMethodNonce
let amountFromTheClient = req.body.amount
//charge
//Backend Code
let newTransaction = gateway.transaction.sale({
amount: amountFromTheClient,
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
}).then(function (result) {
if (result.success) {
res.json(result);
} else {
console.log(result.errors)// error is pointed here in this line
}
}).catch(function (err) {
console.error(err);
});enter code here
}
you are missing the first parameter error in the callback function
let newTransaction = gateway.transaction.sale({
amount: amountFromTheClient,
paymentMethodNonce: nonceFromTheClient,
options: {
submitForSettlement: true
}
}).then(function (error,result) {
if (result.success) {
res.json(result);
} else {
res.status(500).json(error); // error is pointed here in this line
}
}).catch(function (err) {
console.error(err);
});
check this docs
Related
I have the following API, the API is inserting into a table based on user selection from the client. User can select different material belonging to same experiment. In my payload, I have materials as array, experiment as string. I tried several ways to resolve my error. Following was the last try:
app.post("/insertMaterials", (req, res) => {
for (let mat of req.body["material"]) {
try {
oracledb.getConnection(
{
user: "some_user",
password: "some_pw",
connectString: "someConnStr",
},
function (err, connection) {
if (err) {
console.error("1" + err);
return;
}
connection.execute(
"INSERT INTO MATERIALS (ID, MAT_NAME, EXPR) VALUES((SELECT max(ID) + 1 FROM MATERIALS), :1, :2)",
[mat, req.body["experiment"]],
(err, result) => {
if (err) {
console.error("log " + err);
}
connection.commit();
connection.close();
}
);
}
);
} catch (error) {
console.log(error);
}
}
return res.status(200).json({
title: "SUCCESS: Materials Inserted",
});
});
I always get:
triggerUncaughtException(err, true / fromPromise /);
^
[Error: DPI-1002: invalid dpiConn handle] { errorNum: 0, offset: 0 }
Before I had a separate function of the block inside the for loop and I also tried with execeuteMany. Still same error. After trying lot other ways and reading in internet, I couldn't solve the issue. Except for finally catching uncaughtException and logging the error:
process.on('uncaughtException', (error, next) => {
let date = new Date()
errorLogStream.write(`Date: ${date}. Err: ${error.stack} \n`)
return
})
By catching this exception, my program does not break anymore and data is always inserted. But it would be great to know how and when this is raised and how this can be resolved or where if I am doing a mistake.
UPDATE
Payload example: {'material': ['F99999.7', 'J84845.4'], 'experiment': 'NA32R'}
Function:
async function addMatToExpr(exp, mat) {
let connection;
try {
connection = await oracledb.getConnection(
{
user: "some_user",
password: "some_pw",
connectString: "someConnStr",
});
result = await connection.execute("INSERT INTO MATERIALS (ID,
MAT_NAME, EXPR) VALUES((SELECT max(ID) + 1 FROM MATERIALS), :1, :2)",
[exp, mat], { autoCommit: true })
} catch (error) {
return res.status(404).json({
title: error,
});
} finally {
if (connection) {
try {
await connection.close()
} catch(error) {
console.log(error)
}
}
}
}
API:
app.post("/insertMaterials", (req, res) => {
for (let mat of req.body["materials"]) {
addMatToExpr(req.body["experiment"], mat)
}
});
Added the async/await function and the api that calls the function.
You need to 'await' the Oracle function calls so each completes before continuing. Currently the connection is being closed before the statement is executed.
See all the node-oracledb documentation and examples.
E.g.
async function run() {
let connection;
try {
connection = await oracledb.getConnection(dbConfig);
result = await connection.execute(sql, binds, options);
console.dir(result, { depth: null });
} catch (err) {
console.error(err);
} finally {
if (connection) {
try {
await connection.close();
} catch (err) {
console.error(err);
}
}
}
}
I'm trying to learn how to implement transactions for a simple app in Mongoose with express for a RESTful API.
I've managed to put together a small one change function using the mongoDB session.withTransaction() helper function.
This code block runs with no errors and the document appears in the DB as I would expect.
function createCourse() {
try {
return Course.createCollection()
.then(() => mongoose.startSession())
.then(session => {
session.withTransaction(() => {
return Course.create(
[
{
author: "Larry",
category: "web",
tags: ["tag1", "tag2"],
isPublished: false,
price: 15,
name: "Tester series 3"
}
],
{ session }
);
});
});
} catch (error) {
console.error(error);
}
}
I feel like I'm missing something with how to structure my operations with this function.
Putting everything together into an Express POST method, looks like this works but I'd appreciate a code-review of it.
Also, how can I go about testing that the code is correctly handling errors/roll-backs? Put session.abortTransaction(); somewhere within the sesson.withTransaction() block?
router.post("/", async (req, res) => {
try {
validateRental(req.body);
} catch (error) {
return res.status(400).send(error.details[0].message);
}
let customer = null;
try {
customer = await Customers.findById(req.body.customerId);
} catch (err) {
return res.status(400).send("Invalid customer.");
}
let movie = null;
try {
movie = await Movies.findById(req.body.movieId);
} catch (err) {
return res.status(400).send("Invalid movie.");
}
if (movie.numberInStock === 0)
return res.status(400).send("Movie not in stock.");
try {
mongoose.startSession().then(session => {
session.withTransaction(async () => {
let rental = new Rentals({
renter: {
_id: customer._id,
name: customer.name,
phone: customer.phone,
isGold: customer.isGold
},
movie: {
_id: movie._id,
title: movie.title,
dailyRentalRate: movie.dailyRentalRate
}
});
await rental.save({ session });
movie.numberInStock--;
await movie.save({ session });
res.send(rental);
});
});
} catch (err) {
res.status(500).send(err.message);
}
});
I have a PUT request that I'm trying to have hit the backend, but for some reason, it never reaches it. What's odd is the if(req.body.bidderId){} hits no problem, but not the if(req.body.watchingGroup){}
The watching angular service uses identical code to the bidderId so I don't know what's different between the two where only one would reach the endpoint? Whats wrong with the addToWatchList call? I did testing and both console.log statements in code block return the correct value. So the data is ready to be passes, but is never received.
console.log("MADE IT TO LISTINGS BACKEND");
never outputs for watchingGroup scenario
watching.service.ts
addToWatchList(id: string, watchingGroup: string[]) {
const watching: Watching = {
id: id,
watchingGroup: watchingGroup
};
console.log("Here are the values being passed to backend");
console.log(watching.id);
console.log(watching.watchingGroup);
console.log(watching);
return this.http.put(`http://localhost:3000/api/listings/${watching.id}`, watching,
);
}
app.js
app.put("/api/listings/:id", (req, res) => {
console.log("MADE IT TO LISTINGS BACKEND");
if (req.body.biddingGroup) {
console.log("bidding has been received");
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
currentBid: req.body.currentBid,
lastBidTimeStamp: Date.now(),
bidderId: req.body.bidderId,
auctionEndDateTime: req.body.auctionEndDateTime,
biddingGroup: req.body.biddingGroup,
lastBidTimeStamp: req.body.lastBidTimeStamp
},
function(err, docs) {
if (err) res.json(err);
else {
console.log(docs);
}
}
);
}
if (req.body.watchingGroup) {
console.log("watching has been received");
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
watchingGroup: req.body.watchingGroup
},
function(err, docs) {
if (err) res.json(err);
else {
console.log(docs);
}
}
);
}
});
addToWatchList
addToWatchList(
auctionId: string,
watchingGroup: string[]
) {
this.watchItStatus = true;
this.userId = localStorage.getItem("userId: ");
var unique = watchingGroup.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
this.uniqueResult = unique;
watchingGroup.push(this.userId);
this.watchListService.addToWatchList(auctionId, this.uniqueResult);
}
As i suspected you're not subscribing to it. It's weird but you need to subscribe to it.
this.watchListService.addToWatchList(auctionId, this.uniqueResult).subscribe(
(res) => {
// Handle success response
console.log("SUCCESS");
},
(err) => {
// Handle error response
console.log("ERROR");
}
);
I'm using the loopback for backend API, here for fetching the data from MySQL, here while performing the operation on it I am using the async npm library,
to perform block-level functional execution, while doing these facing setback with an autocallBack functional issue.
Unhandled rejection TypeError: autoCallback is not a function
here is my pseudo code.
ModalName.remoteMethod = function (data, cb) {
async.auto({
firstCallingFunction: function (autoCallback) {
ModalName.find({
id: 1
}, yourResult => {
if (err) {
return cb({
success: false,
msg: 'Insufficient parameters',
data: err,
});
} else {
return autoCallback(null, yourResult);
}
});
},
secondCallingFunction: ['firstCallingFunction', function (autoCallback, result) {
console.log('result=====>', result)
ModalName.find({id: result['id']})
.then(function(dbResult) {
if (dbResult) {
console.log('dbResult==========>', dbResult.toJSON());
return autoCallback(null, dbResult);
}
});
}],
}, function (error, autoResult) {
if (error) {
return cb(null, error);
} else {
return cb(null, {
success: true,
msg: 'result fetched',
data: autoResult.secondCallingFunction,
});
}
});
};
Get in ==> err in autoResult's object function is undefined.
Any solution for that issue, please send.
Thanks.
Here is the solution, I just changed the function arguments and it works for me!
ModalName.remoteMethod = function (data, cb) {
async.auto({
firstCallingFunction: function (autoCallback) {
ModalName.find({
id: 1
}, yourResult => {
if (err) {
return autoCallback({
success: false,
msg: 'Insufficient parameters',
data: err,
});
} else {
return autoCallback(null, yourResult);
}
});
},
secondCallingFunction: ['firstCallingFunction', function (result, autoCallback) {
console.log('result=====>', result)
ModalName.find({id: result['id']})
.then(function(dbResult) {
if (dbResult) {
console.log('dbResult==========>', dbResult.toJSON());
return autoCallback(null, dbResult);
}
});
}],
}, function (error, autoResult) {
if (error) {
return cb(null, error);
} else {
return cb(null, {
success: true,
msg: 'result fetched',
data: autoResult.secondCallingFunction,
});
}
});
};
I am currently doing an API in Node.JS with the framework Sails.js. I am using promises for the first time and I have some troubles to sync my promises like I want.
My main function is the following :
createCard: function(req, res) {
checkIfUserHasStripeAccount(req.user)
.then(addCreditCardToStripeAccount())
.then(function cardCreated() {
res.send(200, {
msg: 'Card created'
});
})
.catch(function handleError(err) {
res.send(err.httpCode, err.msg);
})
},
Obviously I can't add a credit card to a stripe account if the user doesn't have one.
The function checkIfUserHasStripeAccount() checks if the account exists and if not, create it.
Here is the code for this part :
function checkIfUserHasStripeAccount(user) {
var deferred = q.defer();
if (!user.idStripe) {
createStripeAccountToUser(user)
.then(function(savedUser) {
deferred.resolve(savedUser);
})
.catch(function(err) {
deferred.reject(err);
})
} else {
deferred.resolve(user);
}
return deferred.promise;
}
function createStripeAccountToUser(user) {
var deferred = q.defer();
var jsonUserToCreate = {
description: user.firstname + ' ' + user.surname,
email: user.email
};
stripe.customers.create(jsonUserToCreate, function(err, customer) {
if (err) {
deferred.reject({
httpCode: 500,
msg: 'some error'
});
} else {
user.idStripe = customer.id;
user.save(function(err, savedUser) {
if (err) {
deferred.reject({
httpCode: 500,
msg: 'some error'
});
}
deferred.resolve(savedUser);
});
}
});
return deferred.promise;
}
The problem is that the .then(addCreditCardToStripeAccount()) is executed before checkIfUserHasStripeAccount() is finished.
I can't figure out why. I thought the .then(addCreditCardToStripeAccount()) would only be executed if it received a reject or resolve.
You are correct in your line of thought.
The problem is that you are invoking your function instead of referencing it:
.then(addCreditCardToStripeAccount())
should be:
.then(addCreditCardToStripeAccount)
I expect this to work:
createCard: function (req, res) {
checkIfUserHasStripeAccount(req.user)
.then(addCreditCardToStripeAccount)
.then(function cardCreated(){
res.send(200, {msg: 'Card created'});
})
.catch(function handleError(err) {
res.send(err.httpCode, err.msg);
})
},
For future, note that the () after the function name invokes the function, as order of execution in JS will evaluate it first due to being inside the then's ().
In promise chains, always invoke only the first function. Example:
function first () { /*...*/ } // All return promise.
function second() { /*...*/ }
function third () { /*...*/ }
first() // Invoked
.then(second) // Not invoked. second() will have been bad here.
.then(third);