mirror of
https://github.com/n08i40k/schedule-parser-next.git
synced 2025-12-06 17:57:45 +03:00
Чистка.
Удалены неиспользуемые функции. Были исправлены несоблюдения стиля кода.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
|
||||
import { AuthGuard } from "./auth.guard";
|
||||
|
||||
// TODO: Найти применение этой функции
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
export const UserId = createParamDecorator((_, context: ExecutionContext) => {
|
||||
return AuthGuard.extractTokenFromRequest(
|
||||
context.switchToHttp().getRequest(),
|
||||
|
||||
@@ -29,7 +29,7 @@ export class AuthGuard implements CanActivate {
|
||||
try {
|
||||
if (
|
||||
!(await this.jwtService.verifyAsync(token)) ||
|
||||
!(await this.usersService.has({ access_token: token }))
|
||||
!(await this.usersService.contains({ accessToken: token }))
|
||||
) {
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
throw new Error();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
ArgumentMetadata,
|
||||
Injectable,
|
||||
PipeTransform,
|
||||
UnauthorizedException,
|
||||
@@ -16,12 +15,12 @@ export class UserFromTokenPipe implements PipeTransform {
|
||||
) {}
|
||||
|
||||
async transform(token: string): Promise<user | null> {
|
||||
const jwt_user: { id: string } = await this.jwtService.decode(token);
|
||||
const jwtUser: { id: string } = await this.jwtService.decode(token);
|
||||
|
||||
if (!jwt_user)
|
||||
if (!jwtUser)
|
||||
throw new UnauthorizedException("Передан некорректный токен!");
|
||||
|
||||
const user = await this.usersService.findUnique({ id: jwt_user.id });
|
||||
const user = await this.usersService.findUnique({ id: jwtUser.id });
|
||||
if (!user)
|
||||
throw new UnauthorizedException("Передан некорректный токен!");
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ export class AuthService {
|
||||
) {}
|
||||
|
||||
async signUp(signUpDto: SignUpDto): Promise<SignUpResultDto> {
|
||||
if (await this.usersService.has({ username: signUpDto.username }))
|
||||
if (await this.usersService.contains({ username: signUpDto.username }))
|
||||
throw new ConflictException(
|
||||
"Пользователь с таким именем уже существует!",
|
||||
);
|
||||
@@ -39,7 +39,7 @@ export class AuthService {
|
||||
username: signUpDto.username,
|
||||
salt: salt,
|
||||
password: await hash(signUpDto.password, salt),
|
||||
access_token: await this.jwtService.signAsync({
|
||||
accessToken: await this.jwtService.signAsync({
|
||||
id: id,
|
||||
}),
|
||||
};
|
||||
@@ -47,7 +47,7 @@ export class AuthService {
|
||||
return this.usersService.create(input).then((user) => {
|
||||
return {
|
||||
id: user.id,
|
||||
access_token: user.access_token,
|
||||
accessToken: user.accessToken,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -66,21 +66,21 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
|
||||
const access_token = await this.jwtService.signAsync({ id: user.id });
|
||||
const accessToken = await this.jwtService.signAsync({ id: user.id });
|
||||
|
||||
await this.usersService.update({
|
||||
where: { id: user.id },
|
||||
data: { access_token: access_token },
|
||||
data: { accessToken: accessToken },
|
||||
});
|
||||
|
||||
return { id: user.id, access_token: access_token };
|
||||
return { id: user.id, accessToken: accessToken };
|
||||
}
|
||||
|
||||
async updateToken(
|
||||
updateTokenDto: UpdateTokenDto,
|
||||
): Promise<UpdateTokenResultDto> {
|
||||
if (
|
||||
!(await this.jwtService.verifyAsync(updateTokenDto.access_token, {
|
||||
!(await this.jwtService.verifyAsync(updateTokenDto.accessToken, {
|
||||
ignoreExpiration: true,
|
||||
}))
|
||||
) {
|
||||
@@ -89,24 +89,24 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
|
||||
const jwt_user: { id: string } = await this.jwtService.decode(
|
||||
updateTokenDto.access_token,
|
||||
const jwtUser: { id: string } = await this.jwtService.decode(
|
||||
updateTokenDto.accessToken,
|
||||
);
|
||||
|
||||
const user = await this.usersService.findUnique({ id: jwt_user.id });
|
||||
if (!user || user.access_token !== updateTokenDto.access_token) {
|
||||
const user = await this.usersService.findUnique({ id: jwtUser.id });
|
||||
if (!user || user.accessToken !== updateTokenDto.accessToken) {
|
||||
throw new NotFoundException(
|
||||
"Некорректный или недействительный токен!",
|
||||
);
|
||||
}
|
||||
|
||||
const access_token = await this.jwtService.signAsync({ id: user.id });
|
||||
const accessToken = await this.jwtService.signAsync({ id: user.id });
|
||||
|
||||
await this.usersService.update({
|
||||
where: { id: user.id },
|
||||
data: { access_token: access_token },
|
||||
data: { accessToken: accessToken },
|
||||
});
|
||||
|
||||
return { access_token: access_token };
|
||||
return { accessToken: accessToken };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,15 +8,12 @@ export class SignInDto extends PickType(UserDto, ["username"]) {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export class SignInResultDto extends PickType(UserDto, [
|
||||
"id",
|
||||
"access_token",
|
||||
]) {}
|
||||
export class SignInResultDto extends PickType(UserDto, ["id", "accessToken"]) {}
|
||||
|
||||
export class SignUpDto extends SignInDto {}
|
||||
|
||||
export class SignUpResultDto extends SignInResultDto {}
|
||||
|
||||
export class UpdateTokenDto extends PickType(UserDto, ["access_token"]) {}
|
||||
export class UpdateTokenDto extends PickType(UserDto, ["accessToken"]) {}
|
||||
|
||||
export class UpdateTokenResultDto extends UpdateTokenDto {}
|
||||
|
||||
@@ -24,11 +24,13 @@ export class UserDto {
|
||||
password: string;
|
||||
@ApiProperty({ description: "Последний токен доступа" })
|
||||
@IsJWT()
|
||||
access_token: string;
|
||||
accessToken: string;
|
||||
}
|
||||
|
||||
// TODO: Доделать пользователей
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
export class ClientUserDto extends OmitType(UserDto, [
|
||||
"password",
|
||||
"salt",
|
||||
"access_token",
|
||||
"accessToken",
|
||||
]) {}
|
||||
|
||||
@@ -239,10 +239,6 @@ export class ScheduleParser {
|
||||
});
|
||||
}
|
||||
|
||||
public getLastResult(): ScheduleParseResult | null {
|
||||
return this.lastResult;
|
||||
}
|
||||
|
||||
private getAffectedDays(
|
||||
cachedGroup: GroupDto | null,
|
||||
group: GroupDto,
|
||||
|
||||
@@ -28,11 +28,11 @@ ${response.statusText}`);
|
||||
downloadLink: string;
|
||||
updateDate: string;
|
||||
} {
|
||||
const schedule_block = dom.window.document.getElementById("cont-i");
|
||||
if (schedule_block === null)
|
||||
const scheduleBlock = dom.window.document.getElementById("cont-i");
|
||||
if (scheduleBlock === null)
|
||||
throw new Error("Не удалось найти блок расписаний!");
|
||||
|
||||
const schedules = schedule_block.getElementsByTagName("div");
|
||||
const schedules = scheduleBlock.getElementsByTagName("div");
|
||||
if (schedules === null || schedules.length === 0)
|
||||
throw new Error("Не удалось найти строку с расписанием!");
|
||||
|
||||
@@ -40,11 +40,11 @@ ${response.statusText}`);
|
||||
const link = poltavskaya.getElementsByTagName("a")[0]!;
|
||||
|
||||
const spans = poltavskaya.getElementsByTagName("span");
|
||||
const update_date = spans[3].textContent!.trimStart();
|
||||
const updateDate = spans[3].textContent!.trimStart();
|
||||
|
||||
return {
|
||||
downloadLink: link.href,
|
||||
updateDate: update_date,
|
||||
updateDate: updateDate,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,9 +64,11 @@ ${response.statusText}`);
|
||||
return this.getCachedXLS();
|
||||
|
||||
const dom = await this.getDOM();
|
||||
const parse_data = this.parseData(dom);
|
||||
const parseData = this.parseData(dom);
|
||||
|
||||
const response = await axios.get(parse_data.downloadLink, {
|
||||
// FIX-ME: Что такое Annotator и почему он выдаёт пустое предупреждение?
|
||||
// noinspection Annotator
|
||||
const response = await axios.get(parseData.downloadLink, {
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
if (response.status !== 200) {
|
||||
@@ -77,7 +79,7 @@ ${response.statusText}`);
|
||||
|
||||
const result: XlsDownloaderResult = {
|
||||
fileData: response.data.buffer,
|
||||
updateDate: parse_data.updateDate,
|
||||
updateDate: parseData.updateDate,
|
||||
etag: response.headers["etag"],
|
||||
new:
|
||||
this.cacheMode === XlsDownloaderCacheMode.NONE
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import {
|
||||
ScheduleParser,
|
||||
ScheduleParseResult,
|
||||
} from "./internal/schedule-parser/schedule-parser";
|
||||
import { ScheduleParser } from "./internal/schedule-parser/schedule-parser";
|
||||
import { BasicXlsDownloader } from "./internal/xls-downloader/basic-xls-downloader";
|
||||
import { XlsDownloaderCacheMode } from "./internal/xls-downloader/xls-downloader.base";
|
||||
import { ScheduleDto } from "../dto/schedule.dto";
|
||||
|
||||
@@ -10,10 +10,6 @@ export class UsersService {
|
||||
return this.prismaService.user.findUnique({ where: where });
|
||||
}
|
||||
|
||||
async findOne(where: Prisma.userWhereInput): Promise<user | null> {
|
||||
return this.prismaService.user.findFirst({ where: where });
|
||||
}
|
||||
|
||||
async update(params: {
|
||||
where: Prisma.userWhereUniqueInput;
|
||||
data: Prisma.userUpdateInput;
|
||||
@@ -25,7 +21,7 @@ export class UsersService {
|
||||
return this.prismaService.user.create({ data });
|
||||
}
|
||||
|
||||
async has(where: Prisma.userWhereUniqueInput): Promise<boolean> {
|
||||
async contains(where: Prisma.userWhereUniqueInput): Promise<boolean> {
|
||||
return (await this.prismaService.user.count({ where })) > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ export class ObjectIdPipe implements PipeTransform<any, string> {
|
||||
)
|
||||
throw new BadRequestException("Invalid ObjectId");
|
||||
|
||||
const return_string = value.toLowerCase();
|
||||
if (!/^[0-9a-f]{24}$/.test(return_string))
|
||||
const returnString = value.toLowerCase();
|
||||
if (!/^[0-9a-f]{24}$/.test(returnString))
|
||||
throw new BadRequestException("Invalid ObjectId");
|
||||
|
||||
return return_string;
|
||||
return returnString;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
type Nullable<T> = {
|
||||
[P in keyof T]: T[P] | null | Array<any>;
|
||||
};
|
||||
|
||||
export function convertToPrismaInput<T>(dto: Nullable<T>): T {
|
||||
return Object.entries(dto)
|
||||
.filter((x) => x[1] !== undefined)
|
||||
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}) as T;
|
||||
}
|
||||
@@ -1,31 +1,3 @@
|
||||
export function trimAll(str: string): string {
|
||||
return str.replace(/\s\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
const customLessonIdxToTextPresets = [
|
||||
"Первое",
|
||||
"Второе",
|
||||
"Третье",
|
||||
"Четвёртое",
|
||||
"Пятое",
|
||||
"Шестое",
|
||||
"Седьмое",
|
||||
];
|
||||
|
||||
export function customLessonIdxToText(num: number): string {
|
||||
return customLessonIdxToTextPresets[num];
|
||||
}
|
||||
|
||||
const defaultLessonIdxToTextPresets = [
|
||||
"Первая",
|
||||
"Вторая",
|
||||
"Третья",
|
||||
"Четвёртая",
|
||||
"Пятая",
|
||||
"Шестая",
|
||||
"Седьмая",
|
||||
];
|
||||
|
||||
export function defaultLessonIdxToText(num: number): string {
|
||||
return defaultLessonIdxToTextPresets[num];
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export class ClassValidatorInterceptor implements NestInterceptor {
|
||||
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler<any>,
|
||||
next: CallHandler,
|
||||
): Observable<any> | Promise<Observable<any>> {
|
||||
return next.handle().pipe(
|
||||
map(async (returnValue: any) => {
|
||||
@@ -71,6 +71,7 @@ export class ClassValidatorInterceptor implements NestInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
// noinspection FunctionNamingConventionJS
|
||||
export function ResultDto(type: any) {
|
||||
return (target: NonNullable<unknown>, propertyKey: string | symbol) => {
|
||||
Reflect.defineMetadata("design:result-dto", type, target, propertyKey);
|
||||
|
||||
Reference in New Issue
Block a user