DEV Community

Pheak Pheasa
Pheak Pheasa

Posted on

Using postgresql with nuxt3 by ORM(sequelize)

Certainly! Using an ORM (Object-Relational Mapping) library can simplify database interactions by abstracting away SQL queries and providing an object-oriented interface to interact with the database. In the Node.js ecosystem, sequelize is a popular ORM for PostgreSQL.

Here's how you can set up Nuxt.js 3 with Sequelize for PostgreSQL:

  1. Install Sequelize and PostgreSQL Driver:
bashCopy codenpm install sequelize pg pg-hstore
  1. Configuration:

Create a Sequelize instance and configure it to connect to your PostgreSQL database. You can do this in a separate file, such as sequelize.js, and import it where needed.

javascriptCopy code// sequelize.js

import { Sequelize } from 'sequelize';

const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'postgres',
});

export default sequelize;

Replace 'database', 'username', 'password', and 'localhost' with your actual database credentials.

  1. Define Models:

Create Sequelize models to represent your database tables. These models define the structure of your data and provide methods for interacting with it.

javascriptCopy code// models/User.js

import { DataTypes } from 'sequelize';
import sequelize from '../sequelize';

const User = sequelize.define('User', {
  firstName: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  lastName: {
    type: DataTypes.STRING,
    allowNull: false,
  },
});

export default User;
  1. Usage in Nuxt.js:

You can now use Sequelize models in your Nuxt.js application to perform database operations. For example, in your Vuex store:

javascriptCopy code// store/index.js

import User from '~/models/User';

export const actions = {
  async fetchUsers({ commit }) {
    try {
      const users = await User.findAll();
      commit('SET_USERS', users);
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  },
};
  1. Migration and Seeding:

Sequelize supports database migrations and seeders, which allow you to manage your database schema and seed initial data. You can create migration files to define changes to your database schema and run them using Sequelize CLI.

bashCopy codenpx sequelize-cli migration:generate --name create-users

This will create a new migration file where you can define the changes to your database schema.

javascriptCopy code// migrations/YYYYMMDDHHMMSS-create-users.js

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      firstName: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      lastName: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  },
};

After defining the migration, you can apply it to the database:

bashCopy codenpx sequelize-cli db:migrate

For seeding initial data, you can create seeder files and run them using Sequelize CLI as well.

bashCopy codenpx sequelize-cli seed:generate --name demo-users

This will create a new seeder file where you can define the initial data.

javascriptCopy code// seeders/YYYYMMDDHHMMSS-demo-users.js

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.bulkInsert('Users', [
      {
        firstName: 'John',
        lastName: 'Doe',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        firstName: 'Jane',
        lastName: 'Doe',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]);
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.bulkDelete('Users', null, {});
  },
};

Then, run the seeder:

bashCopy codenpx sequelize-cli db:seed:all

These are the basic steps to set up Nuxt.js 3 with Sequelize for PostgreSQL. Adjustments might be needed based on your specific requirements and application structure.

Top comments (0)