fix: format

This commit is contained in:
GitBluub
2023-09-20 23:54:04 +02:00
parent 162fc9148f
commit 82403c811e
11 changed files with 107 additions and 75 deletions

View File

@@ -45,9 +45,9 @@ export class AuthController {
@Post('register') @Post('register')
async register(@Body() registerDto: RegisterDto): Promise<void> { async register(@Body() registerDto: RegisterDto): Promise<void> {
try { try {
const user = await this.usersService.createUser(registerDto) const user = await this.usersService.createUser(registerDto);
await this.settingsService.createUserSetting(user.id); await this.settingsService.createUserSetting(user.id);
} catch(e) { } catch (e) {
console.error(e); console.error(e);
throw new BadRequestException(); throw new BadRequestException();
} }
@@ -116,25 +116,28 @@ export class AuthController {
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiBearerAuth() @ApiBearerAuth()
@ApiOkResponse({description: 'Successfully edited settings', type: Setting}) @ApiOkResponse({ description: 'Successfully edited settings', type: Setting })
@ApiUnauthorizedResponse({description: 'Invalid token'}) @ApiUnauthorizedResponse({ description: 'Invalid token' })
@Patch('me/settings') @Patch('me/settings')
udpateSettings( udpateSettings(
@Request() req: any, @Request() req: any,
@Body() settingUserDto: UpdateSettingDto): Promise<Setting> { @Body() settingUserDto: UpdateSettingDto,
): Promise<Setting> {
return this.settingsService.updateUserSettings({ return this.settingsService.updateUserSettings({
where: { userId: +req.user.id}, where: { userId: +req.user.id },
data: settingUserDto, data: settingUserDto,
}); });
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiBearerAuth() @ApiBearerAuth()
@ApiOkResponse({description: 'Successfully edited settings', type: Setting}) @ApiOkResponse({ description: 'Successfully edited settings', type: Setting })
@ApiUnauthorizedResponse({description: 'Invalid token'}) @ApiUnauthorizedResponse({ description: 'Invalid token' })
@Get('me/settings') @Get('me/settings')
async getSettings(@Request() req: any): Promise<Setting> { async getSettings(@Request() req: any): Promise<Setting> {
const result = await this.settingsService.getUserSetting({ userId: +req.user.id }); const result = await this.settingsService.getUserSetting({
userId: +req.user.id,
});
if (!result) throw new NotFoundException(); if (!result) throw new NotFoundException();
return result; return result;
} }

View File

@@ -1,9 +1,9 @@
import { ApiProperty } from "@nestjs/swagger"; import { ApiProperty } from '@nestjs/swagger';
export class SearchHistoryDto { export class SearchHistoryDto {
@ApiProperty() @ApiProperty()
query: string; query: string;
@ApiProperty() @ApiProperty()
type: "song" | "artist" | "album" | "genre"; type: 'song' | 'artist' | 'album' | 'genre';
} }

View File

@@ -1,5 +1,5 @@
import { ApiProperty } from "@nestjs/swagger"; import { ApiProperty } from '@nestjs/swagger';
import { IsNumber } from "class-validator"; import { IsNumber } from 'class-validator';
export class SongHistoryDto { export class SongHistoryDto {
@ApiProperty() @ApiProperty()
@@ -15,8 +15,8 @@ export class SongHistoryDto {
score: number; score: number;
@ApiProperty() @ApiProperty()
difficulties: Record<string, number> difficulties: Record<string, number>;
@ApiProperty() @ApiProperty()
info: Record<string, number> info: Record<string, number>;
} }

View File

@@ -20,7 +20,7 @@ import { SearchHistoryDto } from './dto/SearchHistoryDto';
@Controller('history') @Controller('history')
@ApiTags('history') @ApiTags('history')
export class HistoryController { export class HistoryController {
constructor(private readonly historyService: HistoryService) { } constructor(private readonly historyService: HistoryService) {}
@Get() @Get()
@HttpCode(200) @HttpCode(200)
@@ -52,14 +52,17 @@ export class HistoryController {
return this.historyService.createSongHistoryRecord(record); return this.historyService.createSongHistoryRecord(record);
} }
@Post("search") @Post('search')
@HttpCode(201) @HttpCode(201)
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@ApiUnauthorizedResponse({description: "Invalid token"}) @ApiUnauthorizedResponse({ description: 'Invalid token' })
async createSearchHistory( async createSearchHistory(
@Request() req: any, @Request() req: any,
@Body() record: SearchHistoryDto @Body() record: SearchHistoryDto,
): Promise<void> { ): Promise<void> {
await this.historyService.createSearchHistoryRecord(req.user.id, { query: record.query, type: record.type }); await this.historyService.createSearchHistoryRecord(req.user.id, {
} query: record.query,
type: record.type,
});
}
} }

View File

@@ -2,17 +2,17 @@ import { Test, TestingModule } from '@nestjs/testing';
import { HistoryService } from './history.service'; import { HistoryService } from './history.service';
describe('HistoryService', () => { describe('HistoryService', () => {
let service: HistoryService; let service: HistoryService;
beforeEach(async () => { beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({ const module: TestingModule = await Test.createTestingModule({
providers: [HistoryService], providers: [HistoryService],
}).compile(); }).compile();
service = module.get<HistoryService>(HistoryService); service = module.get<HistoryService>(HistoryService);
}); });
it('should be defined', () => { it('should be defined', () => {
expect(service).toBeDefined(); expect(service).toBeDefined();
}); });
}); });

View File

@@ -6,7 +6,7 @@ import { SongHistoryDto } from './dto/SongHistoryDto';
@Injectable() @Injectable()
export class HistoryService { export class HistoryService {
constructor(private prisma: PrismaService) { } constructor(private prisma: PrismaService) {}
async createSongHistoryRecord({ async createSongHistoryRecord({
songID, songID,
@@ -74,7 +74,7 @@ export class HistoryService {
async createSearchHistoryRecord( async createSearchHistoryRecord(
userID: number, userID: number,
{ query, type }: SearchHistoryDto { query, type }: SearchHistoryDto,
): Promise<SearchHistory> { ): Promise<SearchHistory> {
return this.prisma.searchHistory.create({ return this.prisma.searchHistory.create({
data: { data: {

View File

@@ -2,43 +2,55 @@ import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { PrismaService } from './prisma/prisma.service'; import { PrismaService } from './prisma/prisma.service';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, ValidationPipe } from '@nestjs/common'; import {
import {RequestLogger, RequestLoggerOptions} from 'json-logger-service'; CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
ValidationPipe,
} from '@nestjs/common';
import { RequestLogger, RequestLoggerOptions } from 'json-logger-service';
import { tap } from 'rxjs'; import { tap } from 'rxjs';
@Injectable() @Injectable()
export class AspectLogger implements NestInterceptor { export class AspectLogger implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) { intercept(context: ExecutionContext, next: CallHandler) {
const req = context.switchToHttp().getRequest(); const req = context.switchToHttp().getRequest();
const res = context.switchToHttp().getResponse(); const res = context.switchToHttp().getResponse();
const { statusCode } = context.switchToHttp().getResponse(); const { statusCode } = context.switchToHttp().getResponse();
const { originalUrl, method, params, query, body, user} = req; const { originalUrl, method, params, query, body, user } = req;
const toPrint = { const toPrint = {
originalUrl, originalUrl,
method, method,
params, params,
query, query,
body, body,
"userId": user?.id ?? "not logged in", userId: user?.id ?? 'not logged in',
"username": user?.username ?? "not logged in", username: user?.username ?? 'not logged in',
}; };
return next.handle().pipe( return next.handle().pipe(
tap((data) => tap((data) =>
console.log(JSON.stringify({ console.log(
...toPrint, JSON.stringify({
statusCode, ...toPrint,
data statusCode,
})) data,
) }),
); ),
} ),
);
}
} }
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.use(RequestLogger.buildExpressRequestLogger({ doNotLogPaths: ['/health'] } as RequestLoggerOptions)); app.use(
RequestLogger.buildExpressRequestLogger({
doNotLogPaths: ['/health'],
} as RequestLoggerOptions),
);
const prismaService = app.get(PrismaService); const prismaService = app.get(PrismaService);
await prismaService.enableShutdownHooks(app); await prismaService.enableShutdownHooks(app);

View File

@@ -21,11 +21,14 @@ import { SearchService } from './search.service';
@ApiTags('search') @ApiTags('search')
@Controller('search') @Controller('search')
export class SearchController { export class SearchController {
constructor(private readonly searchService: SearchService) { } constructor(private readonly searchService: SearchService) {}
@Get('songs/:query') @Get('songs/:query')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
async searchSong(@Request() req: any, @Param('query') query: string): Promise<Song[] | null> { async searchSong(
@Request() req: any,
@Param('query') query: string,
): Promise<Song[] | null> {
try { try {
const ret = await this.searchService.songByGuess(query, req.user?.id); const ret = await this.searchService.songByGuess(query, req.user?.id);
if (!ret.length) throw new NotFoundException(); if (!ret.length) throw new NotFoundException();
@@ -37,7 +40,10 @@ export class SearchController {
@Get('genres/:query') @Get('genres/:query')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
async searchGenre(@Request() req: any, @Param('query') query: string): Promise<Genre[] | null> { async searchGenre(
@Request() req: any,
@Param('query') query: string,
): Promise<Genre[] | null> {
try { try {
const ret = await this.searchService.genreByGuess(query, req.user?.id); const ret = await this.searchService.genreByGuess(query, req.user?.id);
if (!ret.length) throw new NotFoundException(); if (!ret.length) throw new NotFoundException();
@@ -49,7 +55,10 @@ export class SearchController {
@Get('artists/:query') @Get('artists/:query')
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
async searchArtists(@Request() req: any, @Param('query') query: string): Promise<Artist[] | null> { async searchArtists(
@Request() req: any,
@Param('query') query: string,
): Promise<Artist[] | null> {
try { try {
const ret = await this.searchService.artistByGuess(query, req.user?.id); const ret = await this.searchService.artistByGuess(query, req.user?.id);
if (!ret.length) throw new NotFoundException(); if (!ret.length) throw new NotFoundException();
@@ -58,4 +67,4 @@ export class SearchController {
throw new InternalServerErrorException(); throw new InternalServerErrorException();
} }
} }
} }

View File

@@ -5,7 +5,10 @@ import { PrismaService } from 'src/prisma/prisma.service';
@Injectable() @Injectable()
export class SearchService { export class SearchService {
constructor(private prisma: PrismaService, private history: HistoryService) { } constructor(
private prisma: PrismaService,
private history: HistoryService,
) {}
async songByGuess(query: string, userID: number): Promise<Song[]> { async songByGuess(query: string, userID: number): Promise<Song[]> {
return this.prisma.song.findMany({ return this.prisma.song.findMany({

View File

@@ -3,8 +3,8 @@ import { SettingsService } from './settings.service';
import { PrismaModule } from 'src/prisma/prisma.module'; import { PrismaModule } from 'src/prisma/prisma.module';
@Module({ @Module({
imports: [PrismaModule], imports: [PrismaModule],
providers: [SettingsService], providers: [SettingsService],
exports: [SettingsService], exports: [SettingsService],
}) })
export class SettingsModule {} export class SettingsModule {}

View File

@@ -20,10 +20,10 @@ export class SettingsService {
user: { user: {
connect: { connect: {
id: userId, id: userId,
} },
} },
} },
}) });
} }
async updateUserSettings(params: { async updateUserSettings(params: {
@@ -37,7 +37,9 @@ export class SettingsService {
}); });
} }
async deleteUserSettings(where: Prisma.UserSettingsWhereUniqueInput): Promise<UserSettings> { async deleteUserSettings(
where: Prisma.UserSettingsWhereUniqueInput,
): Promise<UserSettings> {
return this.prisma.userSettings.delete({ return this.prisma.userSettings.delete({
where, where,
}); });