Currently, I am in the process of building a web application using Docker and incorporating Express along with JavaScript. For structuring my project, I have opted for a Three-layered architecture pattern and leveraging Sequelize to interact with MySQL for database queries. Specifically, I have a 'blogpost' resource that is linked to an 'accounts' table. Here's a snippet showcasing this relation:
const Account = sequelize.define('accounts', {
personId: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
username: {
type: Sequelize.STRING(50),
allowNull: false,
unique: true
},
email: {
type: Sequelize.STRING(50),
allowNull: false,
unique: true
},
userPassword: Sequelize.TEXT
}, {
timestamps: false
})
const Blogpost = sequelize.define('blogposts', {
blogId: {
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
title: Sequelize.TEXT,
content: Sequelize.TEXT,
posted: Sequelize.TEXT,
imageFile: Sequelize.TEXT
}, {
timestamps: false
})
Blogpost.belongsTo(Account, {foreignKey: "userId", foreignKeyConstraint: true})
Next up, allow me to walk you through how I retrieve all blogposts within the presentation layer:
router.get("/", function(request, response){
blogManager.getAllBlogposts(function(errors, blogposts){
if(errors.includes("databaseError")){
response.send("<h1>Something went wrong!</h1>")
}
else if(errors.length > 0){
const model = {
errors
}
console.log("blogpostsModel:", { model })
response.render("blogposts.hbs", { model })
}else{
const model = {
blogposts
}
response.render("blogposts.hbs", { model })
}
})
})
Furthermore, let's take a look at how the model appears:
blogposts {
dataValues: {
blogId: 2,
title: 'fsdhkjfsdahflhs',
content: 'fhjkdsfkbmngfhyuxgc',
posted: '275760-07-09',
imageFile: 'module-6.jpg',
userId: 1
},
_previousDataValues: {
blogId: 2,
title: 'fsdhkjfsdahflhs',
content: 'fhjkdsfkbmngfhyuxgc',
posted: '275760-07-09',
imageFile: 'module-6.jpg',
userId: 1
},
blogposts {
dataValues: {
blogId: 3,
title: 'fjhhkjfsa',
content: 'gfhjdsakdasdsa',
posted: '8989-08-09',
imageFile: 'module-6.jpg',
userId: 2
},
_previousDataValues: {
blogId: 3,
title: 'fjhhkjfsa',
content: 'gfhjdsakdasdsa',
posted: '8989-08-09',
imageFile: 'module-6.jpg',
userId: 2
},
Finally, I'm looking into extracting usernames from their respective userids. While I've managed to create a function retrieving a username by userid, I'm uncertain on how to scale it to fetch all usernames based on the provided userids. Any suggestions or solutions would be greatly appreciated!
Thank you for your time and assistance!