show error message on duplicate data insertion in angular 14 - duplicates

`
saveDepartment(): void {
this.submitted = true;
if (this.deptForm.invalid) {
return
}
const data = {
Name: this.Department.name,
SortOrder: this.Department.sortOrder,
MaxStaff: this.Department.shortName,
IsActive: this.Department.isActive
};
this.DepartmentService.create(data)
.subscribe({
next: (res) => {
this.alert = true;
console.log(res);
},
error: (e) => console.error(e)
});
}
`
i need to show error message while inserting the duplicate data to the database

Related

Delete an image of a post stored in a backend folder when i delete a user of a social network application

I have a problem on my application, it is a social network. The user can create a post with a message and an image, stored in a backend images folder thanks to Multer. I use sequelize and MySql. When I delete a post, the image is indeed deleted in the images folder since I use multer in my post deletion function so everything goes well but when I delete the author, since I go through a relationship between tables so that when I delete a user, their posts are deleted. This works but in this case the images are not deleted from the folder they are stored in, since Multer is not in the loop. How do I get the images to be deleted from the images folder too in this specific case? Thank you for your help !
`
// Template for the Post table
const User = require("../models/User");
const Sequelize = require("sequelize");
const database = require("../config/database");
const Post = database.define("post", {
content: { type: Sequelize.STRING, allowNull: false },
image: { type: Sequelize.STRING, allowNull: true },
likes: { type: Sequelize.INTEGER, allowNull: false, default: 0 },
});
module.exports = Post;
// Relationship with the User table
User.hasMany(Post, { onDelete: "CASCADE", foreignKey: "userId" });
Post.belongsTo(User, { onDelete: "CASCADE" });
`
`
// deletePost function
exports.deleteOnePost = (req, res, next) => {
Post.findOne({ where: { id: req.params.id } })
.then((post) => {
if (!post) {
return res.status(404).json({
error: new Error("Post non trouvé !"),
});
}
if (post.userId === req.auth.userId || req.auth.userAdmin) {
if (post.image) {
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
Post.destroy({ where: { id: req.params.id } })
.then(() => res.status(200).json({ message: "Post sans supprimé" }))
.catch((error) => res.status(400).json({ error }));
} else {
return res.status(403).json({
error: new Error("Requête non autorisée !"),
});
}
})
.catch((error) => res.status(500).json({ error }));
};
`
#Anatoly Thank you very much for your help, I'm sorry, I'm a beginner, I tried to adapt what you sent me to the method I use. I don't use the async/await method much and don't know much about it. Do you think I'm getting closer to the solution with what i made ? thanks again !
`
exports.deleteUser = (req, res, next) => {
const userId = req.params.id;
User.findOne({ where: { id: userId } }).then((user) => {
if (!user) {
return res.status(404).json({
error: new Error("User not found!"),
});
}
});
const userPosts = User.getAllPosts();
const postImages = posts.map((x) => x.image).filter((x) => x);
User.destroy({ where: { id: userId } })
.then((post) => {
Post.findOne({ where: { userId } })
.then((post) => {
Post.destroy({ where: { userId } }).then((res) =>
res.status(200).json({
message: "User is deleted",
})
);
for (const image of postImages) {
const filename = image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
})
.catch((error) =>
res.status(400).json({
error,
})
);
})
.catch((error) => res.status(500).json({ error }));
};
`
I don't see how Multer is related to a file deletion. It only helps you to store them. Any way you just need to get all posts of a certain user and delete them and a user in a transaction and then delete their images in a cycle:
// I did not use try/catch for simplicity
exports.deleteUser = async (req, res, next) => {
// get the user id somehow (req.params or the request context, for instance)
const userId = ...
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({
error: new Error("User not found!"),
});
}
const userPosts = await user.getPosts();
const postImages = poists.map(x => x.image).filter(x => x);
// here 'sequelize' is the Sequelize instance, you used to register models
await sequelize,transaction(async transaction => {
await Post.destroy({ where: { userId } })
await User.destroy({ where: { id: userId } })
});
for (const image of postImages) {
const filename = image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
res.status(200).json({ message: "User is deleted" }))
}
I come back to put the fonction that works with my method, i often use ".then()" ".catch()", many thanks to Anatoly for helping me to find the solution, here is the result of my work :
exports.deleteUser = (req, res, next) => {
User.findOne({ where: { id: req.params.id } })
.then((user) => {
if (!user) {
return res.status(404).json({
error: new Error("user not found !"),
});
}
// I get all the posts of the author
Post.findAll({ where: { userId: req.params.id } })
.then((posts) => {
// I start a loop in the posts of the author to find the posts with an image
posts.forEach((post) => {
if (post.image) {
// I erase the files in the images backend directory
const filename = post.image.split("/images/")[1];
fs.unlink(`images/${filename}`, () => {});
}
// Now i can erase the author
User.destroy({ where: { id: req.params.id } })
.then(() =>
res.status(200).json({
message: "User erased !",
})
)
.catch((error) =>
res.status(400).json({
error,
})
);
});
})
.catch((error) =>
res.status(400).json({
error,
})
);
})
.catch((error) => res.status(500).json({ error }));
};

Sequelize showing error: Unexpected token u in JSON at position 0

I am trying to update a record in mysql database using sequelize but it is not working.
I am getting this error
Unexpected token u in JSON at position 0
Model
module.exports = sequelize.define("branches", {
address: Sequelize.TEXT(),
company: Sequelize.STRING(),
codeConfig: {
type: Sequelize.STRING,
allowNull: false,
get: function () {
return JSON.parse(this.getDataValue('codeConfig'));
},
set: function (val) {
return this.setDataValue('codeConfig', JSON.stringify(val));
}
},
});
Update function
router.put('/:id', async (req, res) => {
const { address, company} = req.body;
try {
const branches = await Branches.findOne({ where: { code: req.params.id } });
if (!branches) return res.json({ msg: "Branch Not Found" });
Branches.update({ "address": "No. 10 distreet street" }, {
where: {
code: "WHJ5uBdriI"
}
}).then(function (newBranch) {
return res.json({ msg: "Updated" });
});
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
}
});
Error output
Add autoJsonMap: false, to your sequelize's dialectOptions
Example:
let sequelize = new Sequelize(DATABASE, USER, PASSWORD, {
// some other options
dialectOptions: {
autoJsonMap: false,
}
});
Reference:
https://github.com/sequelize/sequelize/issues/12583
i have noticed that before sequelize make a field update, it fetches through all fields, and then execute a getter function if exist, so for that i added an if check inside a getter, here is the code now the model.update working:
get: function () {
if(this.getDataValue('codeConfig') !== undefined){
/// appentely sequelize tried to parse the value of 'codeConfig' but its undefined since you are updating only address field.
return JSON.parse(this.getDataValue('codeConfig'));
}
},

How to use sweetalert2 preConfirm with httpRequest which needs to be subscribed to within Angular 9 component

I have an Angular form component which sends a http request and subscribes to that request. Now I'm trying to add a sweetalert2 feature to start a loader when the form is submitted (onSubmit()) and the http request is executed (with doSubmit()) and I'd like the sweetalert modal to change to a success or error message when http request returns a response which is subscribed to by the component (resulting in execution of onSuccess() or onError()). For some reason, my swal.preConfirm doesn't change the sweetalert from the loader to a success or error message. Can you please help?
protected doSubmit(): Observable<NewUser> {
swal.queue([{
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
},
preConfirm: () => {
return this.onSuccess()
.then(() =>
swal.insertQueueStep({
title: 'Success'
})
)
.catch(() =>
swal.insertQueueStep({
title: 'Error'
})
)
}
}])
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
}
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
onSuccess(){
return new Promise((resolve){
resolve('success')
})
onError(){
return new Promise((reject){
reject('error')
})
I figured out a bit of a make shift solution for this issue without using swal.preConfirm. Hopefully, there is a more elegant solution to achieving the same. For now, here's my solution:
protected doSubmit(): Observable<NewUser> {
this.invalidOnError = '';
this.navigationExtras = { queryParams: this.asssignToNavExtras.assignToNavExtras({ username: this.username.value }) };
swal.fire({
title: 'Registration',
text: 'Processing your information',
onBeforeOpen: () => {
swal.showLoading()
}
})
.then
return this.httpService.callDatabase<NewUser>('post', '/api/users/register', this.value)
};
onSubmit() {
if (this.form.valid) {
this.doSubmit().subscribe(
() => {
this.error = null;
this.onSuccess();
},
err => {
this.error = err
this.onError();
},
() => {
this.submitted = false;
this.completed = true;
}
)
}
}
protected onSuccess() {
swal.fire({
title: 'Registration Successful',
text: 'Thank you',
icon: 'success',
confirmButtonText: 'OK',
buttonsStyling: false,
customClass: {
confirmButton: 'btn'
},
timer: 10000,
})
}
protected onError() {
swal.fire({
showConfirmButton: false,
timer: 10,
onAfterClose: () => {
code for where to place focus after sweetalert is closed
}
})
}

Vue.js - Store data into session

How do I store my dadta in a session so I can access it in any page? And only destroy the data whenever the page is closed.
Vue.js:
new Vue({
el: '#item-data',
data () {
return {
data:[],
selectedUser:'',
itemCart: [],
quantity: ''
}
},
mounted () {
**** API CALL ****
}
})
.then((response) => {
// handle success
this.data = response.data.items
removeLoader();
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
methods:{
sendInfo(items) {
this.selectedUser = items;
},
addCart: function(cartdets){
this.itemCart.push({cartdets});
console.log(cartdets);
}
}
})
The data i want to store into a session is itemCart[].

Incorrect response after iteration inside for-loop for findById()

I had created 2 tables named: groupusermaps and groups. From groupusermaps i am fetching all the groupId and these groupId I am passing in findById() method to fetch all the details related to that groupId inside the for loop.
here is my method in service:
getAllGroupsByUserId(userId, callback) {
var arr = [];
return sequelize.transaction().then(function(t) {
return groupUserMapModel.GroupUserMap.findAll({
where: {
userId: userId
},
transaction: t
}).then((allGroupsByUserId) => {//from findAll i am getting 2, 1, 4
groupId
for (var p in allGroupsByUserId) {
return
groupModel.Group.findById(allGroupsByUserId[p].groupId, { transaction: t
}).then((group) => {
arr.push(
JSON.stringify(group)
);
});
}
}).then(() => {
callback(arr);
});
});
}
my controller code:
router.get('/controllers/getGroups/user/:userId/groups', (req, res) => {
groupService.getAllGroupsByUserId((req.params.userId), (result) => {
log.info('Group list: ' + JSON.stringify(result));
});
res.send('Fetched all group list');
});
But I am getting an empty array as response from the controller on the console. Is there any way to fix this issue?
groupUserMapModel.GroupUserMap.findAll({
where: {
userId: userId
},
include:[{
model:groupModel
}]
})
.then((results) => {
console.log(results);
})
.catch(err=>{
console.log(err);
})
// provided that groupUserMapModel associated to groupModel
groupUserMapModel.associate = models => {
groupUserMapModel.belongsTo(models.groupModel, {foreignKey: groupId})
}
for more info read about sequelize association