The first thing we’re going to do is to move the houses from the simple JSON file we now have in houses.js
to the new Postgres database we defined, by first creating the Sequelize models for the data, and then letting Sequelize create the tables for us.
The file houses.js
currently hosts this content, which forms all our application data so far:
houses.js
export default [
{
id: 1,
picture: '/img/1.jpg',
type: 'Entire house',
town: 'New York',
title: 'Beautiful flat in New York!',
price: '150.00',
},
{
id: 2,
picture: '/img/2.jpg',
type: 'Entire house',
town: 'Amsterdam',
title: 'A flat in Amsterdam with a great view',
price: '90.00',
},
]
Let’s move this to a Sequelize model in src/model.js
. You can add this code at the bottom of the file, before the export { sequelize, User }
line:
class House extends Sequelize.Model {}
House.init(
{
id: {
type: Sequelize.DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
picture: { type: Sequelize.DataTypes.STRING, allowNull: false },
type: { type: Sequelize.DataTypes.STRING, allowNull: false },
town: { type: Sequelize.DataTypes.STRING, allowNull: false },
title: { type: Sequelize.DataTypes.STRING, allowNull: false },
price: { type: Sequelize.DataTypes.INTEGER, allowNull: false },
owner: { type: Sequelize.DataTypes.INTEGER, allowNull: false },
},
{
sequelize,
modelName: 'house',
timestamps: false,
}
)
The owner
field will contain a reference to a user.
Then add House
to the list of exports:
export { sequelize, User, House }
Great!
Now we can make Sequelize automatically create the houses table by calling House.sync()
. We can add this call into an API call like the one in pages/api/auth/login.js
, temporarily, then we remove it:
import { User, House, sequelize } from '../../../model.js'
//...
export default async (req, res) => {
if (req.method !== 'POST') {
res.status(405).end() //Method Not Allowed
return
}
House.sync()
...
It’s a nice feature that allows us to avoid creating the table separately.
Once you hit the endpoint, you can remove the code from that file, as the table has been created.
If you modify a model, you can call this sync() model method again to keep the table in sync with the model, with the alter
property:
User.sync({ alter: true })
House.sync({ alter: true })
You can add this line at the end of the model.js
file.
The alter: true
option makes sure tables are updated when we change the model, something very useful as we build the app.
The code for this lesson is available at https://github.com/flaviocopes/airbnb-clone-react-nextjs-2020/tree/6-1