이 사용자 정의 기능은 다음과 같은 후속 모델을 가지고 있습니다.
'use strict';
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../../config');
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.STRING,
primaryKey: true
},
name: DataTypes.STRING,
email: DataTypes.STRING,
bio: DataTypes.STRING,
phone: DataTypes.STRING,
username: DataTypes.STRING,
password: {
type: DataTypes.STRING,
set(value){
this.setDataValue('password', bcrypt.hashSync(value, 10));
}
}
}, {});
User.generateJWT = function(id, username) {
return jwt.sign({
id: id,
username: username,
expiresIn: config.auth.exp
}, config.secret);
};
User.toAuthJson = async function() {
return {
name: this.name,
email: this.email,
bio: this.bio,
phone: this.phone,
username: this.username
};
};
User.validatePassword = function(password, passwordHash){
return bcrypt.compareSync(password, passwordHash);
};
User.isUniqueEmail = async function(email) {
return await User.findOne({where: {email}}) === null;
};
User.isUniqueUsername = async function(username) {
return await User.findOne({where: {username}}) === null;
};
User.isUniquePhone = async function(phone) {
return await User.findOne({where: {phone}}) === null;
};
User.associate = function(models) {
// associations can be defined here
};
return User;
};
다음과 같은 컨트롤러:
const {User} = require('../database/models/');
module.exports.register = async (req, res, next) => {
try {
const isUniqueEmail = await User.isUniqueEmail(req.body.email);
if (!isUniqueEmail) return res.status(422).json({'message': 'email already exists'});
const isUniquePhone = await User.isUniquePhone(req.body.phone);
if (!isUniquePhone) return res.status(422).json({'message': 'phone already exists'});
const isUniqueUsername = await User.isUniqueUsername(req.body.username);
if (!isUniqueUsername) return res.status(422).json({'message': 'username already exists'});
const user = await User.create(req.body);
console.log(user.toAuthJson()); //an error occurs here
return res.status(201).json({user: user.toAuthJson()});
}catch (e) {
next(e);
}
};
이 user.toAuthJson과 같은이 컨트롤러에서 toAuthJson 기능에 액세스하려고 할 때. "작은 u를 주목하십시오." TypeError: User.toAuthJson은 함수가 아닙니다. 정상적으로 접근할 수 있어야 합니다. 돕다. 감사 해요
User.toAuthJson
현재 클래스 메서드입니다. 다른 함수와 마찬가지로 다음과 같이 호출해야 합니다 User.toAuthJson(user)
.
아마도 인스턴스 메소드를 찾고 있을 것이므로 대신 프로토타입에서 정의하고 싶을 것입니다.
User.prototype.toAuthJson = function() {
return {
name: this.name,
email: this.email,
bio: this.bio,
phone: this.phone,
username: this.username
};
};
이제 다음 User
과 같이 인스턴스에서 호출할 수 있습니다 .
console.log(user.toAuthJson());
async
이 함수는 비동기식으로 아무것도 하지 않기 때문에 생략했습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다