#typescript #sequelize.js #sequelize-typescript
Вопрос:
Вот моя модель —
import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";
import { IDBUserAttributes } from "./shared/db-table";
interface UserModel extends Model<IDBUserAttributes>, IDBUserAttributes {}
class User extends Model<UserModel, IDBUserAttributes> {}
type UserStatic = typeof Model amp; {
new (values?: object, options?: BuildOptions): UserModel;
};
const UserFactory = (sequelize: Sequelize): UserStatic => {
return <UserStatic>sequelize.define("users", {
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
unique: true,
},
email: {
type: DataTypes.STRING(320),
allowNull: false,
unique: true,
},
username: {
type: DataTypes.STRING(26),
allowNull: false,
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
});
}
export {
UserModel,
User,
UserFactory,
UserStatic,
}
IDBUserAttributes
Есть все поля для проверки типа.
Вот index.ts
файл —
import { UserFactory } from '../user';
import { MovieFactory } from '../movie';
import { FavoriteMoviesFactory } from '../favoriteMovies';
import * as sequelize from "sequelize";
const instantiateObj = {
database: process.env.MYSQL_DB_NAME,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PWD,
port: process.env.MYSQL_PORT,
host: process.env.MYSQL_HOST,
}
const dbConfig = new sequelize.Sequelize(instantiateObj.database, instantiateObj.username, instantiateObj.password, {
port: Number(instantiateObj.port),
host: instantiateObj.host,
dialect: "mysql",
pool: {
min: 0,
max: 5,
acquire: 30000,
idle: 10000,
},
}
);
const User = UserFactory(dbConfig);
const Movie = MovieFactory(dbConfig);
const FavoriteMovies = FavoriteMoviesFactory(dbConfig);
export {
dbConfig,
User,
Movie,
FavoriteMovies,
}
Я хотел бы использовать User.create() or User.build()
без всех полей.
Прямо сейчас я не могу этого сделать из-за того, что IDBUserAttributes
я получаю ошибку —
Argument of type '{ email: string; username: string; password: string; }' is not assignable to parameter of type 'IDBUserAttributes'.
Type '{ email: string; username: string; password: string; }' is missing the following properties from type 'IDBUserAttributes': id, createdAt, updatedAtts(2345)
Я пошел к … https://sequelize.org/master/manual/typescript.html#usage-of—code-sequelize-define—code-
И увидел, что —
// Некоторые поля являются необязательными при вызове UserModel.create() или UserModel.build()
interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}
Как я могу применить это к своему коду?
Ответ №1:
Вы можете указать необязательные поля с помощью объединения:
interface IDBUserCreationAttributes extends Optional<IDBUserAttributes, "id" | "createdAt" | "updatedAt"> {}
class User extends Model<IDBUserAttributes, IDBUserCreationAttributes> {}