I'm used to using Express with React on the backend and working in a server.js file to sync the database. With Next.js, there's no server.js file to sync the models with sequelize. My work around right now is syncing the models upon user login/sign up (see code below), but I know this will cause a bunch of issues down the line. How do I setup my files and sync the models upon a Next.js server start up?
So far this is how I've set up my backend:
./src/pages/api/user/login.js
const { User } = require('../../../db/model');
const { signToken } = require('../../../auth/auth');
const sequelize = require('../../../db/config/connections');
sequelize.sync({ force: false }); //<----- This is where I sync all my models
export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const user = await User.findOne({
where: {
username: req.body.username
}
});
if (!user) {
res.status(400).json({ message: 'Incorrect login credentials' })
return
}
const password = await user.checkPassword(req.body.password)
if (!password) {
res.status(400).json({ message: 'Incorrect login credentials' })
return
}
const token = signToken(user)
res.status(200).json({ token, user })
} catch (err) {
console.log(err);
res.status(400).json(err)
}
} else {
res.status(400).json({ message: 'Invalid request' })
}
}
./src/db/model/user.js
const { Model, DataTypes } = require("sequelize");
const sequelize = require("../config/connections");
const bcrypt = require("bcrypt");
class User extends Model {
checkPassword(loginPassword) {
return bcrypt.compareSync(loginPassword, this.password);
}
}
User.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: {
msg: "Email already in use!",
},
validate: {
isEmail: {
msg: "Please enter a valid email address",
},
},
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [8, 30],
msg: "Password must be between 8 and 30 characters",
},
},
},
},
{
hooks: {
beforeCreate: async (newUser) => {
newUser.password = await bcrypt.hash(newUser.password, 10);
return newUser;
},
beforeUpdate: async (updateUser) => {
if (updateUser.password) {
updateUser.password = await bcrypt.hash(updateUser.password, 10);
}
return updateUser;
},
},
sequelize,
timestamps: false,
freezeTableName: true,
underscored: true,
modelName: "hungry_user",
}
);
module.exports = User;
./src/db/config/connections.js
require("dotenv").config();
const Sequelize = require("sequelize");
const sequelize = process.env.JAWSDB_URL
? new Sequelize(process.env.JAWSDB_URL)
: new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
host: "127.0.0.1",
dialect: "mysql",
port: 3306,
}
);
module.exports = sequelize;
The tables are able to sync, but I want them to sync upon starting the server.
I got the same issue
my workaround was to do every thing via CLI commands
In this order:
1- Run > npx sequelize-cli migration:generate --name first-setup
to generate skeleton for first migration
2- Call dbConfig.sequelize.sync({ force: true });
inside up method
3- Run > npx sequelize-cli db:migrate
4- Run > npx sequelize-cli seed:generate --name first-seed
to generate skeleton for first seed
5- Fill seeding script with your logic than
6- Run npx sequelize db:seed --seed [...seedName].js --debug
Note: for more details about Sequelize CLI migrations/seeding
Check out: https://sequelize.org/docs/v6/other-topics/migrations/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.