Getters
const User = sequelize.define('user', {
username: {
type: DataTypes.STRING,
get() {
const rawValue = this.getDataValue('username');
return rawValue ? rawValue.toUpperCase() : null;
}
}
});
const user = User.build({ username: 'SuperUser123' });
console.log(user.username);
console.log(user.getDataValue('username'));
Setters
const User = sequelize.define('user', {
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
set(value) {
this.setDataValue('password', hash(value));
}
}
});
const user = User.build({ username: 'someone', password: 'NotSo§tr0ngP4$SW0RD!' });
console.log(user.password);
console.log(user.getDataValue('password'));
const User = sequelize.define('user', {
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
set(value) {
this.setDataValue('password', hash(this.username + value));
}
}
});
getters, setters를 동시에 사용 가능
const { gzipSync, gunzipSync } = require('zlib');
const Post = sequelize.define('post', {
content: {
type: DataTypes.TEXT,
get() {
const storedValue = this.getDataValue('content');
const gzippedBuffer = Buffer.from(storedValue, 'base64');
const unzippedBuffer = gunzipSync(gzippedBuffer);
return unzippedBuffer.toString();
},
set(value) {
const gzippedBuffer = gzipSync(value);
this.setDataValue('content', gzippedBuffer.toString('base64'));
}
}
});
Virtuals
- DB에 존재하지 않은 컬럼을 모델에서 가상 필드로 만들어서 사용할 수 있다
const User = sequelize.define('user', {
firstName: DataTypes.TEXT,
lastName: DataTypes.TEXT,
fullName: {
type: DataTypes.VIRTUAL,
get() {
return `${this.firstName} ${this.lastName}`;
},
set(value) {
throw new Error('Do not try to set the `fullName` value!');
}
}
});
const user = await User.create({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName);