We need to create a database to track airplane status and data with specific requirements:
File: migrations/XXXXXX-create-airplane.js
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Airplanes', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
airlineCode: {
type: Sequelize.STRING,
allowNull: false
},
flightNumber: {
type: Sequelize.STRING,
allowNull: false
},
inService: {
type: Sequelize.BOOLEAN,
defaultValue: true
},
maxNumPassengers: {
type: Sequelize.INTEGER,
allowNull: false
},
currentNumPassengers: {
type: Sequelize.INTEGER
},
firstFlightDate: {
type: Sequelize.DATE
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
// Add unique constraint for airlineCode + flightNumber
await queryInterface.addConstraint('Airplanes', {
fields: ['airlineCode', 'flightNumber'],
type: 'unique',
name: 'unique_airline_flight'
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Airplanes');
}
};
File: models/airplane.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Airplane = sequelize.define('Airplane', {
airlineCode: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
},
flightNumber: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
},
inService: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
maxNumPassengers: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
min: 0
}
},
currentNumPassengers: {
type: DataTypes.INTEGER,
validate: {
passengerCountValid(value) {
// Cannot exceed max passengers
if (value > this.maxNumPassengers) {
throw new Error('Current passengers cannot exceed maximum');
}
// Must be null if not in service
if (!this.inService && value !== null) {
throw new Error('Current passengers must be null when not in service');
}
}
}
},
firstFlightDate: {
type: DataTypes.DATE
}
}, {});
return Airplane;
};
To verify our implementation:
npx sequelize-cli db:migratenpm testThis database design mirrors real airline systems that need to:
Try these additional challenges: