Add registration and data caching

This commit is contained in:
2024-06-15 18:25:29 +04:00
parent f43dc5f11b
commit 56a0841322
31 changed files with 477 additions and 202 deletions

View File

@@ -7,36 +7,27 @@ export abstract class FilesService {
public static async UploadCover(cover: File) {
const formData = new FormData();
formData.append("cover", cover);
return await HTTPService.post(
`/files/cover`,
coverNameSchema,
formData,
{},
false
);
return await HTTPService.post(`/files/cover`, coverNameSchema, {
body: formData,
stringify: false,
});
}
public static async UploadTorrent(torrent: File) {
const formData = new FormData();
formData.append("torrent", torrent);
return await HTTPService.post(
`/files/torrent`,
torrentNameSchema,
formData,
{},
false
);
return await HTTPService.post(`/files/torrent`, torrentNameSchema, {
body: formData,
stringify: false,
});
}
public static async UploadFragment(fragment: File) {
const formData = new FormData();
formData.append("fragment", fragment);
return await HTTPService.post(
`/files/audio`,
fragmentNameSchema,
formData,
{},
false
);
return await HTTPService.post(`/files/audio`, fragmentNameSchema, {
body: formData,
stringify: false,
});
}
}

View File

@@ -1,4 +1,4 @@
import { HTTPService } from "@/shared/utils/http";
import { HTTPService, RequestCacheOptions } from "@/shared/utils/http";
import { audiobookCardsSchema } from "./schemas/audiobookCard";
import {
AudiobookCreateType,
@@ -17,17 +17,40 @@ import { ItemService } from "../item";
@staticImplements<IItemService>()
export abstract class AudiobookService {
public static cacheTag = "all_audiobooks";
public static urlPrefix = "audiobooks";
private static cacheOptions(custom_tag?: string): RequestCacheOptions {
return {
next: {
tags: custom_tag ? [this.cacheTag, custom_tag] : [this.cacheTag],
revalidate: 60 * 5,
},
};
}
public static async GetCards() {
return await HTTPService.get("/audiobooks/cards", audiobookCardsSchema);
return await HTTPService.get(
`/${this.urlPrefix}/cards`,
audiobookCardsSchema,
this.cacheOptions(`/${this.urlPrefix}/cards`)
);
}
public static async Get(id: number) {
return await HTTPService.get(`/audiobooks/${id}`, audiobookSchema);
return await HTTPService.get(
`/${this.urlPrefix}/${id}`,
audiobookSchema,
this.cacheOptions(`/${this.urlPrefix}/${id}`)
);
}
public static async Add(info: AudiobookCreateType) {
return await HTTPService.post(`/audiobooks`, audiobookSchema, info);
return await HTTPService.post(`/${this.urlPrefix}`, audiobookSchema, {
body: info,
});
}
public static async Change(id: number, info: AudiobookCreateType) {
return await HTTPService.put(`/audiobooks/${id}`, audiobookSchema, info);
return await HTTPService.put(`/${this.urlPrefix}/${id}`, audiobookSchema, {
body: info,
});
}
public static GetEmpty(): AudiobookCreateType {

View File

@@ -44,14 +44,14 @@ export const audiobookSchema = audiobookBaseSchema.merge(
);
export type AudiobookType = z.infer<typeof audiobookSchema>;
export const isAudiobook = (a: any): a is AudiobookType => {
export const isAudiobookStrict = (a: any): a is AudiobookType => {
return audiobookSchema.safeParse(a).success;
};
export const audiobooksSchema = z.array(z.any()).transform((a) => {
const audiobooks: AudiobookType[] = [];
a.forEach((e) => {
if (isAudiobook(e)) audiobooks.push(audiobookSchema.parse(e));
if (isAudiobookStrict(e)) audiobooks.push(audiobookSchema.parse(e));
else console.error("Audiobook parse error - ", e);
});
return audiobooks;

View File

@@ -36,8 +36,5 @@ export const audiobookCardsSchema = z.array(z.any()).transform((a) => {
});
export const isAudiobook = (a: any): a is AudiobookCardType => {
return (
audiobookCardBaseSchema.safeParse(a).success &&
(a as AudiobookCardType).type === TypesOfItems.audiobook
);
return (a as AudiobookCardType).type === TypesOfItems.audiobook;
};

View File

@@ -1,4 +1,4 @@
import { HTTPService } from "@/shared/utils/http";
import { HTTPService, RequestCacheOptions } from "@/shared/utils/http";
import { gameCardsSchema } from "./schemas/gameCard";
import { GameCreateType, gameSchema, GameType } from "./schemas/game";
import {
@@ -13,17 +13,40 @@ import { ItemService } from "../item";
@staticImplements<IItemService>()
export abstract class GameService {
public static cacheTag = "all_games";
public static urlPrefix = "games";
private static cacheOptions(custom_tag?: string): RequestCacheOptions {
return {
next: {
tags: custom_tag ? [this.cacheTag, custom_tag] : [this.cacheTag],
revalidate: 60 * 5,
},
};
}
public static async GetCards() {
return await HTTPService.get("/games/cards", gameCardsSchema);
return await HTTPService.get(
`/${this.urlPrefix}/cards`,
gameCardsSchema,
this.cacheOptions(`/${this.urlPrefix}/cards`)
);
}
public static async Get(id: number) {
return await HTTPService.get(`/games/${id}`, gameSchema);
return await HTTPService.get(
`/${this.urlPrefix}/${id}`,
gameSchema,
this.cacheOptions(`/${this.urlPrefix}/${id}`)
);
}
public static async Add(info: GameCreateType) {
return await HTTPService.post(`/games`, gameSchema, info);
return await HTTPService.post(`/${this.urlPrefix}`, gameSchema, {
body: info,
});
}
public static async Change(id: number, info: GameCreateType) {
return await HTTPService.put(`/games/${id}`, gameSchema, info);
return await HTTPService.put(`/${this.urlPrefix}/${id}`, gameSchema, {
body: info,
});
}
public static GetEmpty(): GameCreateType {

View File

@@ -4,7 +4,7 @@ import { gameCardBaseSchema } from "./gameCard";
export const gameBaseSchema = gameCardBaseSchema.merge(
z.object({
torrent_file: z.string().min(3, "У раздачи должен быть .torrent файл"),
trailer: z.string().optional(),
trailer: z.string().optional().nullable(),
system: z.string().optional().nullable(),
processor: z.string().optional().nullable(),
@@ -49,14 +49,14 @@ export const gameSchema = gameBaseSchema.merge(
);
export type GameType = z.infer<typeof gameSchema>;
export const isGame = (a: any): a is GameType => {
export const isGameStrict = (a: any): a is GameType => {
return gameSchema.safeParse(a).success;
};
export const gamesSchema = z.array(z.any()).transform((a) => {
const games: GameType[] = [];
a.forEach((e) => {
if (isGame(e)) games.push(gameSchema.parse(e));
if (isGameStrict(e)) games.push(gameSchema.parse(e));
else console.error("Game parse error - ", e);
});
return games;

View File

@@ -36,8 +36,5 @@ export const gameCardsSchema = z.array(z.any()).transform((a) => {
});
export const isGame = (a: any): a is GameCardType => {
return (
gameCardBaseSchema.safeParse(a).success &&
(a as GameCardType).type === TypesOfItems.game
);
return (a as GameCardType).type === TypesOfItems.game;
};

View File

@@ -1,13 +1,9 @@
import { ZodSchema } from "zod";
import { gameCreateSchema, gameSchema } from "./game/schemas/game";
import { movieCreateSchema, movieSchema } from "./movie/schemas/movie";
import { gameCreateSchema } from "./game/schemas/game";
import { movieCreateSchema } from "./movie/schemas/movie";
import { MovieService } from "./movie/movie";
import { HTTPService } from "@/shared/utils/http";
import { GameService } from "./game/game";
import {
audiobookCreateSchema,
audiobookSchema,
} from "./audiobook/schemas/audiobook";
import { audiobookCreateSchema } from "./audiobook/schemas/audiobook";
import { AudiobookService } from "./audiobook/audiobook";
import {
IItemService,
@@ -19,6 +15,7 @@ import {
TypesOfItems,
UnionItemType,
} from "./types";
import { EraseCacheByTag } from "@/shared/utils/http";
export abstract class ItemService {
private static get itemsConfiguration(): {
@@ -26,11 +23,7 @@ export abstract class ItemService {
sectionUrl: ItemSectionsType;
formResolver: ZodSchema;
propertiesDescription: ItemPropertiesDescriptionType<UnionItemType>;
AddItem: (itemInfo: ItemCreateType) => Promise<ItemType | null>;
ChangeItem: (
id: number,
itemInfo: ItemCreateType
) => Promise<ItemType | null>;
service: IItemService;
};
} {
return {
@@ -38,57 +31,63 @@ export abstract class ItemService {
sectionUrl: "games",
formResolver: gameCreateSchema,
propertiesDescription: GameService.propertiesDescription,
AddItem: async (itemInfo) =>
await HTTPService.post(`/games`, gameSchema, itemInfo),
ChangeItem: async (id: number, itemInfo) =>
await HTTPService.put(`/games/${id}`, gameSchema, itemInfo),
service: GameService,
},
[TypesOfItems.movie]: {
sectionUrl: "movies",
formResolver: movieCreateSchema,
propertiesDescription: MovieService.propertiesDescription,
AddItem: async (itemInfo) =>
await HTTPService.post(`/movies`, movieSchema, itemInfo),
ChangeItem: async (id: number, itemInfo) =>
await HTTPService.put(`/movies/${id}`, movieSchema, itemInfo),
service: MovieService,
},
[TypesOfItems.audiobook]: {
sectionUrl: "audiobooks",
formResolver: audiobookCreateSchema,
propertiesDescription: AudiobookService.propertiesDescription,
AddItem: async (itemInfo) =>
await HTTPService.post(`/audiobooks`, audiobookSchema, itemInfo),
ChangeItem: async (id: number, itemInfo) =>
await HTTPService.put(`/audiobooks/${id}`, audiobookSchema, itemInfo),
service: AudiobookService,
},
};
}
static get itemSections(): {
[k in ItemSectionsType]: {
sectionName: string;
itemType: TypesOfItems;
popularSubsectionName: string;
sectionInviteText: string;
addItemText: string;
sectionDescription: string;
service: IItemService;
};
} {
return {
games: {
sectionName: "Игры",
itemType: TypesOfItems.game,
popularSubsectionName: "Популярные игры",
sectionInviteText: 'Перейти в раздел "Игры"',
addItemText: "Добавить игру",
sectionDescription:
"каталог .torrent файлов для обмена актуальными версиями популярных игр",
service: GameService,
},
movies: {
sectionName: "Фильмы",
itemType: TypesOfItems.movie,
popularSubsectionName: "Популярные фильмы",
sectionInviteText: 'Перейти в раздел "Фильмы"',
addItemText: "Добавить фильм",
sectionDescription:
"каталог .torrent файлов для обмена популярными фильмами в лучшем качестве",
service: MovieService,
},
audiobooks: {
sectionName: "Аудиокниги",
itemType: TypesOfItems.audiobook,
popularSubsectionName: "Популярные аудиокниги",
sectionInviteText: 'Перейти в раздел "Аудиокниги"',
addItemText: "Добавить аудиокнигу",
sectionDescription:
"каталог .torrent файлов для обмена популярными аудиокнигами любимых авторов",
service: AudiobookService,
},
};
@@ -120,12 +119,29 @@ export abstract class ItemService {
}
public static async AddItem(itemInfo: ItemCreateType) {
return await this.itemsConfiguration[itemInfo.type].AddItem(itemInfo);
const item = await this.itemsConfiguration[itemInfo.type].service.Add(
itemInfo
);
if (item)
EraseCacheByTag(
`/${this.itemsConfiguration[itemInfo.type].service.urlPrefix}/${
item.id
}`
);
return item;
}
public static async ChangeItem(id: number, itemInfo: ItemCreateType) {
return await this.itemsConfiguration[itemInfo.type].ChangeItem(
const item = await this.itemsConfiguration[itemInfo.type].service.Change(
id,
itemInfo
);
if (item)
EraseCacheByTag(
`/${this.itemsConfiguration[itemInfo.type].service.urlPrefix}/${
item.id
}`
);
return item;
}
}

View File

@@ -1,4 +1,4 @@
import { HTTPService } from "@/shared/utils/http";
import { HTTPService, RequestCacheOptions } from "@/shared/utils/http";
import { movieCardsSchema } from "./schemas/movieCard";
import { MovieCreateType, movieSchema, MovieType } from "./schemas/movie";
import {
@@ -13,17 +13,40 @@ import { ItemService } from "../item";
@staticImplements<IItemService>()
export abstract class MovieService {
public static cacheTag = "all_movies";
public static urlPrefix = "movies";
private static cacheOptions(custom_tag?: string): RequestCacheOptions {
return {
next: {
tags: custom_tag ? [this.cacheTag, custom_tag] : [this.cacheTag],
revalidate: 60 * 5,
},
};
}
public static async GetCards() {
return await HTTPService.get("/movies/cards", movieCardsSchema);
return await HTTPService.get(
`/${this.urlPrefix}/cards`,
movieCardsSchema,
this.cacheOptions(`/${this.urlPrefix}/cards`)
);
}
public static async Get(id: number) {
return await HTTPService.get(`/movies/${id}`, movieSchema);
return await HTTPService.get(
`/${this.urlPrefix}/${id}`,
movieSchema,
this.cacheOptions(`/${this.urlPrefix}/${id}`)
);
}
public static async Add(info: MovieCreateType) {
return await HTTPService.post(`/movies`, movieSchema, info);
return await HTTPService.post(`/${this.urlPrefix}`, movieSchema, {
body: info,
});
}
public static async Change(id: number, info: MovieCreateType) {
return await HTTPService.put(`/movies/${id}`, movieSchema, info);
return await HTTPService.put(`/${this.urlPrefix}/${id}`, movieSchema, {
body: info,
});
}
public static GetEmpty(): MovieCreateType {

View File

@@ -4,7 +4,7 @@ import { movieCardBaseSchema } from "./movieCard";
export const movieBaseSchema = movieCardBaseSchema.merge(
z.object({
torrent_file: z.string().min(3, "У раздачи должен быть .torrent файл"),
trailer: z.string().optional(),
trailer: z.string().optional().nullable(),
language: z.string().optional().nullable(),
subtitles: z.string().optional().nullable(),
@@ -46,14 +46,14 @@ export const movieSchema = movieBaseSchema.merge(
);
export type MovieType = z.infer<typeof movieSchema>;
export const isMovie = (a: any): a is MovieType => {
export const isMovieStrict = (a: any): a is MovieType => {
return movieSchema.safeParse(a).success;
};
export const moviesSchema = z.array(z.any()).transform((a) => {
const games: MovieType[] = [];
a.forEach((e) => {
if (isMovie(e)) games.push(movieSchema.parse(e));
if (isMovieStrict(e)) games.push(movieSchema.parse(e));
else console.error("Movie parse error - ", e);
});
return games;

View File

@@ -36,8 +36,5 @@ export const movieCardsSchema = z.array(z.any()).transform((a) => {
});
export const isMovie = (a: any): a is MovieCardType => {
return (
movieCardBaseSchema.safeParse(a).success &&
(a as MovieCardType).type === TypesOfItems.movie
);
return (a as MovieCardType).type === TypesOfItems.movie;
};

View File

@@ -49,6 +49,8 @@ export type ItemPropertiesDescriptionType<T extends ItemType | ItemCreateType> =
}[][];
export interface IItemService {
cacheTag: string;
urlPrefix: string;
GetCards(): Promise<ItemCardType[] | null>;
Get(id: number): Promise<ItemType | null>;
Add(info: ItemCreateType): Promise<ItemType | null>;

View File

@@ -1,16 +1,28 @@
import {
loginFormSchema,
loginFormFieldNames,
LoginForm,
} from "./schemas/auth";
LoginFormType,
} from "./schemas/login";
import {
registrationFormSchema,
registrationFormFieldNames,
RegistrationFormType,
RegistrationFormFields,
} from "./schemas/registration";
import { userSchema, User } from "./schemas/user";
import { UserService } from "./user";
export {
loginFormSchema,
loginFormFieldNames,
registrationFormSchema,
registrationFormFieldNames,
UserService,
userSchema,
type User,
type LoginForm,
type LoginFormType,
type RegistrationFormType,
type RegistrationFormFields,
};

View File

@@ -0,0 +1,13 @@
import { z } from "zod";
export const loginFormSchema = z.object({
username: z.string().min(3, "Логин слишком короткий"),
password: z.string().min(3, "Пароль слишком короткий"),
});
export type LoginFormType = z.infer<typeof loginFormSchema>;
export type LoginFormFieldsType = keyof LoginFormType;
export const loginFormFieldNames: { [key in LoginFormFieldsType]: string } = {
username: "Логин",
password: "Пароль",
};

View File

@@ -0,0 +1,20 @@
import { z } from "zod";
export const registrationFormSchema = z.object({
email: z
.string()
.min(3, "Почта слишком короткий")
.email("Это не адрес электронной почты"),
name: z.string().min(3, "Логин слишком короткий"),
password: z.string().min(3, "Пароль слишком короткий"),
});
export type RegistrationFormType = z.infer<typeof registrationFormSchema>;
export type RegistrationFormFields = keyof RegistrationFormType;
export const registrationFormFieldNames: {
[key in RegistrationFormFields]: string;
} = {
email: "E-mail",
name: "Логин",
password: "Пароль",
};

View File

@@ -1,16 +1,6 @@
import { z } from "zod";
import { userSchema } from "./user";
export const loginFormSchema = z.object({
username: z.string().min(3, "Логин слишком короткий"),
password: z.string().min(3, "Пароль слишком короткий"),
});
export const loginFormFieldNames = {
username: "Логин",
password: "Пароль",
};
export type LoginForm = z.infer<typeof loginFormSchema>;
export const tokenResponseSchema = z
.object({
access_token: z.string(),

View File

@@ -1,35 +1,45 @@
import { HTTPService } from "@/shared/utils/http";
import {
LoginForm,
TokenData,
tokenDataSchema,
TokenResponse,
tokenResponseSchema,
} from "./schemas/auth";
import { LoginFormType } from "./schemas/login";
import { jwtDecode } from "jwt-decode";
import Cookies from "js-cookie";
import {
TokenData,
tokenDataSchema,
tokenResponseSchema,
} from "./schemas/token";
import { RegistrationFormType } from "./schemas/registration";
export abstract class UserService {
public static async Login(loginForm: LoginForm) {
public static async Registration(registrationForm: RegistrationFormType) {
const accessToken = await HTTPService.post(
"/auth",
"/auth/registration",
tokenResponseSchema,
new URLSearchParams(Object.entries(loginForm)),
{
"Content-Type": "application/x-www-form-urlencoded",
},
false
{ body: registrationForm }
);
if (accessToken) {
const tokenData = this.DecodeToken(accessToken);
return this.ProcessToken(accessToken);
}
public static async Login(loginForm: LoginFormType) {
const accessToken = await HTTPService.post("/auth", tokenResponseSchema, {
body: new URLSearchParams(Object.entries(loginForm)),
headers: { "Content-Type": "application/x-www-form-urlencoded" },
stringify: false,
});
return this.ProcessToken(accessToken);
}
private static ProcessToken(token: string | null) {
if (token) {
const tokenData = this.DecodeToken(token);
if (tokenData) {
Cookies.set("access-token", accessToken, {
Cookies.set("access-token", token, {
secure: true,
expires: tokenData.expire,
});
return tokenData;
}
}
return null;
}
public static GetToken(): string | undefined {