Files
yourpart3/backend/services/BaseService.js
2024-09-27 07:40:06 +02:00

69 lines
2.1 KiB
JavaScript

import User from '../models/community/user.js';
import UserParam from '../models/community/user_param.js';
import UserParamType from '../models/type/user_param.js';
import UserParamVisibility from '../models/community/user_param_visibility.js';
import UserParamVisibilityType from '../models/type/user_param_visibility.js';
import { Op } from 'sequelize';
class BaseService {
async getUserByHashedId(hashedId) {
const user = await User.findOne({ where: { hashedId } });
if (!user) {
throw new Error('User not found');
}
return user;
}
async getUserById(userId) {
const user = await User.findOne({ where: { id: userId } });
if (!user) {
throw new Error('User not found');
}
return user;
}
async getUserParams(userId, paramDescriptions) {
return await UserParam.findAll({
where: { userId },
include: [
{
model: UserParamType,
as: 'paramType',
where: { description: { [Op.in]: paramDescriptions } }
},
{
model: UserParamVisibility,
as: 'param_visibilities',
include: [
{
model: UserParamVisibilityType,
as: 'visibility_type'
}
]
}
]
});
}
calculateAge(birthdate) {
const birthDate = new Date(birthdate);
const ageDifMs = Date.now() - birthDate.getTime();
const ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
async isUserAdult(userId) {
const birthdateParam = await this.getUserParams(userId, ['birthdate']);
if (!birthdateParam || birthdateParam.length === 0) {
return false;
}
const birthdate = birthdateParam[0].value;
const age = this.calculateAge(birthdate);
return age >= 18;
}
}
export default BaseService;