Skip to content

Commit

Permalink
chore: one to one relationship
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmadlaiq committed Apr 25, 2024
1 parent c30ce91 commit f355d59
Show file tree
Hide file tree
Showing 5 changed files with 171 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const cors = require('cors');
const CategoriesRouter = require('./routes/catagories');
const AuthRouter = require('./routes/auth');
const ProductRouter = require('./routes/product');
const ProfileRouter = require('./routes/profile');
const morgan = require('morgan');
const {errorHandler, notFound} = require('./middleware/errorMiddleware');
const cookieParser = require('cookie-parser');
Expand All @@ -24,6 +25,7 @@ app.use('/public/uploads', express.static(path.join(__dirname + '/public/uploads
app.use('/api/v1/categories', CategoriesRouter);
app.use('/api/v1/auth', AuthRouter);
app.use('/api/v1/products', ProductRouter);
app.use('/api/v1/profiles', ProfileRouter);

// Error handling
app.use(notFound);
Expand Down
51 changes: 51 additions & 0 deletions controllers/profileController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const asyncHandle = require('../middleware/asyncHandle');
const {
Profile
} = require("../models");

//update or create profile data for user with userId
exports.updateOrCreateProfile = asyncHandle(async (req, res) => {
const {
age,
bio,
address,
} = req.body;

const idUser = req.user.id;

const profile = await Profile.findOne({
where: {
userId: idUser
}
});

let message = "";

if (profile) {
await Profile.update({
age,
bio,
address
}, {
where: {
userId: idUser
}
});

message = "Profile updated successfully";
} else {
await Profile.create({
age,
bio,
address,
userId: idUser
});

message = "Profile created successfully";
}

res.status(200).json({
status: "success",
message: message
});
});
49 changes: 49 additions & 0 deletions migrations/20240425041201-create-profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Profiles', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4
},
age: {
type: Sequelize.INTEGER,
allowNull: false
},
bio: {
type: Sequelize.TEXT
},
address: {
type: Sequelize.STRING,
allowNull: false
},
image: {
type: Sequelize.STRING,
},
userId: {
type: Sequelize.UUID,
allowNull: false,
references: {
model: 'Users',
key: 'id'
},
onDelete: 'CASCADE',
onUpdate: 'CASCADE'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Profiles');
}
};
57 changes: 57 additions & 0 deletions models/profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Profile extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Profile.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
age: {
type: DataTypes.INTEGER,
allowNull: false
},
bio: {
type: DataTypes.TEXT
},
address: {
type: DataTypes.STRING,
allowNull: false
},
image: {
type: DataTypes.STRING,
},
userId: {
type: DataTypes.UUID,
allowNull: false,
validate : {
notNull : {
msg : "userId is required"
},
isExist(value) {
return sequelize.models.User.findByPk(value).then((user) => {
if (!user) {
throw new Error('User not found');
}
});
}
}
}
}, {
sequelize,
modelName: 'Profile',
});
return Profile;
};
12 changes: 12 additions & 0 deletions routes/profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const express = require('express');
const router = express.Router();

const {
updateOrCreateProfile
} = require('../controllers/profileController');

const {authMiddleware} = require('../middleware/userMiddleware');

router.post('/', authMiddleware, updateOrCreateProfile);

module.exports = router;

0 comments on commit f355d59

Please sign in to comment.