Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "FEATURE: lending관련 코드 작성중" #42

Merged
merged 1 commit into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions src/books/entities/bookInfo.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,40 +27,33 @@ export class BookInfo {
id: number;

@Column()
@Expose({ groups: ['findAll'] })
title: string;

@Column()
@Exclude()
author: string;

@Column()
@Exclude()
publisher: string;

@Column({
nullable: true,
})
@Exclude()
isbn: string;

@Column()
@Exclude()
image: string;

@Column({
type: 'enum',
enum: BookCategory,
default: BookCategory.WEB_PROGRAMMING,
})
@Exclude()
category: BookCategory;

@Column({
type: 'date',
nullable: true,
})
@Exclude()
publishedAt: Date;

@Exclude()
Expand All @@ -87,7 +80,6 @@ export class BookInfo {
@Expose({ name: 'publishedAt', groups: ['detail'] })
getDate() {
const date = new Date(this.publishedAt);
console.log(date);
return date.getFullYear() + '년 ' + date.getMonth() + '월';
}
}
6 changes: 1 addition & 5 deletions src/lendings/dto/create-lending.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
export class CreateLendingDto {
condition: string;
userId: number;
bookId: number;
}
export class CreateLendingDto {}
16 changes: 3 additions & 13 deletions src/lendings/entities/lending.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { User } from '../../users/entities/user.entity';
import { Returning } from '../../returns/entities/return.entity';
import { Book } from '../../books/entities/book.entity';
import { Exclude, Expose } from 'class-transformer';
import { Exclude } from 'class-transformer';

@Entity()
export class Lending {
Expand All @@ -21,39 +21,29 @@ export class Lending {
}

@PrimaryGeneratedColumn()
@Exclude()
id: number;

@Column({ default: '' })
@Expose({groups:['findAll']})
@Exclude()
condition: string;

@CreateDateColumn()
@Expose({groups:['findAll']})
createdAt: Date;

@UpdateDateColumn()
@Exclude()
updatedAt: Date;

@Expose({groups:['findAll']})
@ManyToOne(() => User, (user) => user.lendings)
user: User;

@ManyToOne(() => User, (librarian) => librarian.librarianLendings)
@Exclude()
librarian: User;

@Expose({groups:['findAll']})
@ManyToOne(() => Book, (book) => book.lendings)
book: Book;

@OneToOne(() => Returning, (returning) => returning.lending)
@Exclude
returning: Returning;

@Expose({ name: 'dueDate', groups: ['findAll'] })
getDate() {
const date = new Date(this.createdAt);
return date.getFullYear() + '.' + date.getMonth() + '.' + date.getDate() + '.';
}
}
24 changes: 5 additions & 19 deletions src/lendings/lendings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,26 @@ import {
Param,
Delete,
Query,
UseGuards,
Req,
UseInterceptors,
ClassSerializerInterceptor,
SerializeOptions,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { LendingsService } from './lendings.service';
import { UpdateLendingDto } from './dto/update-lending.dto';
import { Lending } from './entities/lending.entity';
import { CreateLendingDto } from './dto/create-lending.dto';

@Controller('lendings')
export class LendingsController {
constructor(private readonly lendingsService: LendingsService) {}

@UseGuards(JwtAuthGuard)
@Post()
async create(@Req() req, @Body() createLendingDto: CreateLendingDto) {
// const librarianId = req.user.id;
const librarianId = 1; //
return this.lendingsService.create(createLendingDto, librarianId);
create(@Query('bookId') bookId: string, @Query('userId') userId: string) {
return this.lendingsService.create(+bookId, +userId);
}
@SerializeOptions({ groups: ['findAll'] })
@UseInterceptors(ClassSerializerInterceptor)

@Get()
async findAll() {
findAll() {
return this.lendingsService.findAll();
}

@SerializeOptions({ groups: ['find'] })
@UseInterceptors(ClassSerializerInterceptor)
@Get(':id')
async findOne(@Param('id') id: string) {
findOne(@Param('id') id: string) {
return this.lendingsService.findOne(+id);
}

Expand Down
73 changes: 8 additions & 65 deletions src/lendings/lendings.service.ts
Original file line number Diff line number Diff line change
@@ -1,83 +1,26 @@
import {
BadRequestException,
Injectable,
MethodNotAllowedException,
NotFoundException,
} from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { UpdateLendingDto } from './dto/update-lending.dto';
import { Connection, getConnection, getManager, Repository } from 'typeorm';
import { Repository } from 'typeorm';
import { Lending } from './entities/lending.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/users/entities/user.entity';
import { CreateLendingDto } from './dto/create-lending.dto';

async function checkLendingCnt(userId: number) {
const userData = await getConnection().getRepository('User').findOne(userId);
if (userData == undefined) return 0;
const today: Date = new Date();
const penalty: Date = new Date(userData['penaltiyAt']);
if (2 <= userData['lendingCnt'] || today <= penalty) return 0;
return 1;
}

async function checkLibrarian(librarianId: number) {
const librarian = await getConnection()
.getRepository('User')
.findOne(librarianId);
if (librarian == undefined) return 0;
if (!librarian['librarian']) return 0;
return 1;
}

@Injectable()
export class LendingsService {
constructor(
private connection: Connection,
@InjectRepository(Lending)
private readonly lendingsRepository: Repository<Lending>,
) {}

async create(dto: CreateLendingDto, librarianId: number) {
if (
!(await checkLendingCnt(dto.userId)) ||
!(await checkLibrarian(librarianId))
)
throw new BadRequestException(dto.userId || librarianId);
// TODO : 생성자 사용해서 줄이기
try {
await this.connection.transaction(async (manager) => {
await manager.insert(Lending, {
condition: dto.condition,
user: { id: dto.userId },
librarian: { id: librarianId },
book: { id: dto.bookId },
});
await manager.update(User, dto.userId, {
lendingCnt: () => 'lendingCnt + 1',
});
});
} catch (e) {
throw new Error("lendings.service.create() catch'");
}
async create(bookId: number, userId: number) {
return 'This action adds a new lending';
}

// TODO : 페이지네이션, 시리얼라이제이션
async findAll() {
return await this.lendingsRepository.find({
relations: ['user', 'librarian', 'book', 'returning', 'book.info'],
where: { returning: null },
});
findAll() {
return `This action returns all lendings`;
}
// TODO : 페이지네이션, 시리얼라이제이션
async findOne(lendingId: number) {
const lendingData = await this.lendingsRepository.findOne({
relations: ['user', 'librarian', 'book', 'returning', 'book.info'],
where: { id: lendingId },
});
if (lendingData == undefined || lendingData['returning'])
throw new NotFoundException();
return lendingData;

findOne(lendingId: number) {
return `This action returns a #${lendingId} lending`;
}

update(id: number, updateLendingDto: UpdateLendingDto) {
Expand Down
4 changes: 1 addition & 3 deletions src/users/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export class User {
id: number;

@Column()
@Expose({ groups: ['findAll'] })
login: string;

@Column()
Expand All @@ -34,11 +33,10 @@ export class User {
slack: string;

@Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })
@Expose({ groups: ['findAll'] })
@Exclude()
penaltiyAt: Date;

@Column({ default: 0 })
@Exclude()
lendingCnt: number;

@Column({ default: 0 })
Expand Down