如何在 NodeJS 中从 export.function 调用 export.function?



我有一个像这样声明的控制器函数。根据我对这个函数的评论,我需要调用一个数据库方法来获取当前用户数据,但我想为此重用 exports.function。


我想调用这个getme函数:

// Get the profile of the current user through JWT.
exports.getme = (req, res) => {
db.User.findOne({
where: { id: req.user.id },
include: [
{
model: db.Role,
as: "role"
},
{
model: db.UserType,
as: "userType"
},
{
model: db.PushToken,
as: "pushToken"
},
{
model: db.StripeAccount,
as: "stripeAccount"
}
],
attributes: defaultAttributes
})
.then(data => {
res.send(data)
})
.catch(err => {
console.log(err)
res.status(500).send({
message: "An error has occured while retrieving data."
})
})
}

从这个createStripeAccount函数。

// Create Stripe Account
// If there's no stripeAccount connected to the current user,
// only then will we attempt to call stripe's create.
exports.createStripeAccount = (req, res) => {
stripe.accounts.create({
type: 'express',
country: 'US',
email: req.user.email
})
.then(account => {
console.log('Account: ', JSON.stringify(account))
stripe.accountLinks.create({
account: account.id,
refresh_url: 'https://app.com/reauth',
return_url: 'https://app.com/return',
type: 'account_onboarding',
})
.then(accountLinks => {
console.log('Account links: ', accountLinks.url)
return res.send(accountLinks)
})
.catch(err => {
console.log("Error fetching account links from Stripe: ", err.message);
return res.status(500).send({
message: err.message || "An error has occured while fetching account links from Stripe."
});
})
}).catch(err => {
console.log("Error creating Stripe account: ", err.message);
return res.status(500).send({
message: err.message || "An error has occured while creating Stripe account."
});
});
};

先定义函数,然后再导出。

function getme() {
// ...
}
function createStripeAccount() {
// ...
getme(...);
// ...
}
exports.getme = getme;
exports.createStripeAccount = createStripeAccount;

createStripeAccount函数中任何你想使用的地方使用this.getme(...)

最新更新