1. Installing and Configuring Sequelize
First, ensure that Node.js and Sails.js are installed in your project before using Sequelize. Next, install Sequelize and the required database drivers via npm, such as PostgreSQL, MySQL, or SQLite.
bashnpm install sequelize npm install pg pg-hstore # For PostgreSQL example
2. Initializing Sequelize
Create a service in Sails.js to initialize Sequelize. Create a file named SequelizeService.js in the api/services directory with the following content:
javascriptconst Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'host', dialect: 'postgres', // Adjust based on the database type pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }); module.exports = sequelize;
This code initializes Sequelize and exports it as a module for use in other parts of your Sails.js application.
3. Creating Models
Create model files in the api/models directory. For example, create a file named User.js to define the user model:
javascriptconst Sequelize = require('sequelize'); const sequelize = require('../services/SequelizeService'); const User = sequelize.define('user', { username: { type: Sequelize.STRING, allowNull: false }, email: { type: Sequelize.STRING, allowNull: false }, password: { type: Sequelize.STRING, allowNull: false } }); module.exports = User;
This defines a simple user model with fields for username, email, and password.
4. Using Models
You can use this model in api/controllers for database operations. For example, to create a user:
javascriptconst User = require('../models/User'); module.exports = { async createUser(req, res) { try { const { username, email, password } = req.allParams(); const user = await User.create({ username, email, password }); return res.ok(user); } catch (error) { return res.serverError(error); } } };
5. Configuring Routes
Add routes in config/routes.js to call this controller method:
javascript'POST /user': 'UserController.createUser',
This completes the basic setup for using Sequelize in Sails.js. You can extend these examples as needed for different models and controller methods. This process provides flexibility in integrating Sequelize into your Sails.js project while leveraging its powerful features, such as model associations and transaction handling.