fix(user): persist updateUser correctly; add setup:api script and README update; seeders tweaks
This commit is contained in:
@@ -1,12 +1,27 @@
|
||||
const slug = require("slug");
|
||||
const DB = require('../../database/mysql');
|
||||
var crypto = require('crypto');
|
||||
|
||||
const { User } = DB;
|
||||
|
||||
class UserService {
|
||||
static async createUser(data) {
|
||||
if (typeof data.username === 'undefined') {
|
||||
data.username = UserService.slugify(`${data.firstname.charAt(0)}${data.lastname.charAt(0)}`);
|
||||
}
|
||||
const {salt, hash} = await UserService.generateSaltHash(data.password);
|
||||
data.salt = salt;
|
||||
data.hash = hash;
|
||||
data.role = 'User';
|
||||
return User.create(data);
|
||||
}
|
||||
|
||||
static async generateSaltHash(password) {
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, 10000, 512, 'sha512').toString('hex');
|
||||
return {salt, hash};
|
||||
}
|
||||
|
||||
static async getAllUsers() {
|
||||
return User.findAll({
|
||||
order: [['createdAt', 'DESC']],
|
||||
@@ -36,14 +51,19 @@ class UserService {
|
||||
return user.getArticleIdArticles(searchOptions);
|
||||
}
|
||||
|
||||
static async getFavoritesCount(user) {
|
||||
return user.countArticleIdArticles();
|
||||
}
|
||||
|
||||
static async getUserFollowed(user) {
|
||||
// Sequelize generated method for "users this user follows" is named
|
||||
// `getUserIdUserFollowers()` (see `src/database/relationships/index.js`).
|
||||
return user.getUserIdUserFollowers();
|
||||
}
|
||||
|
||||
static async getFavoritesCount(user) {
|
||||
return user.countArticleIdArticles();
|
||||
static async isUsernameUsed(username) {
|
||||
const user = await User.findOne({ where: { username: username } });
|
||||
return !!user;
|
||||
}
|
||||
|
||||
static async addFavoriteArticle(user, article) {
|
||||
@@ -53,9 +73,25 @@ class UserService {
|
||||
static async removeFavoriteArticle(user, article) {
|
||||
return user.removeArticleIdArticles(article);
|
||||
}
|
||||
|
||||
static slugify(stringToSlug) {
|
||||
return slug(`${stringToSlug}`) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
|
||||
}
|
||||
|
||||
static async updateUser(data) {
|
||||
return User.update(data);
|
||||
static async updateUserById(data, id) {
|
||||
// If `data` is a Sequelize instance, prefer instance.save()
|
||||
try {
|
||||
if (data && typeof data.save === 'function') {
|
||||
const saved = await data.save();
|
||||
return saved;
|
||||
}
|
||||
} catch {
|
||||
// fallthrough to update
|
||||
}
|
||||
|
||||
// Otherwise perform a standard update and return the refreshed instance
|
||||
await User.update(data, { where: { id: id } });
|
||||
return User.findByPk(id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user