Im trying to make sure that the post request doest happen if the body doesn't contain a subscription object. This is for a shopping cart that allows both one-time payments and subscriptions. The problem is when a user that has a subscription come back to the site to buy a one-time payment item this functions will replace the value in the database with "null" because it creates a new object everything the user checkouts. This is stripe based and trying to avoid using webhooks.
frontend
let { data, error } = useSWR(
router.query.session_id
? `/api/checkout_sessions/${router.query.session_id}`
: null,
fetchGetJSON
);
if (error) return <div>failed to load</div>;
if (state && state.token) {
const submitStripInfo = async () => {
if (data == undefined) {
return;
}
const token = JSON.parse(localStorage.getItem("auth")!);
// console.log("token", );
axios({
method: "post",
url: `${baseUrl}`,
data: data,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
Authorization: "Bearer " + token.token,
},
})
.then((res) => {
console.log("response", res.data.result);
data = undefined;
alert(res.data.result);
})
.catch((error) => {
console.log("error", error);
});
if (state.user) {
console.log("user is here");
console.log(data);
}
};
submitStripInfo();
}
Backend code(NODE)
export const createSubscription = async (req, res) => {
// console.log("req_data", JSON.stringify(req.body));
try {
const subscriptions = JSON.stringify(req.body.subscription, null, 4);
console.log(subscriptions)
const user = await User.findByIdAndUpdate(req.user._id, {
subscriptions: {subscriptions},
},
);
if (!user)
return res
.status(400)
.send("User not found")
.save();
console.log("success");
return res.json({subscriptions,
result: 'successfuls'});
} catch (error) {
console.log(error);
}
};