Skip to content

Commit

Permalink
fix!: typeorm migrate 작성하기 (#84)
Browse files Browse the repository at this point in the history
* feat: typeorm migrate 위한 파일 정리 및 config 수정

* refactor: 파일 경로 변경에 의한 import 변경

* migrate: typeorm migrate 성공

* [autofix.ci] apply automated fixes

* chore: readme migration 방법 추가

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
jimin52 and autofix-ci[bot] authored Dec 22, 2024
1 parent feeb8f4 commit f393135
Show file tree
Hide file tree
Showing 40 changed files with 422 additions and 539 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ $ pnpm dev

위 명령어로 개발용 docker compose를 실행합니다.

### migrate 실행
```sh
$ pnpm run migrate:run
```
위 명령어로 migration 실행합니

![](./swagger.webp)

<http://localhost:3000/api> 경로에 접근하여 API 명세가 올바르게 표시되는지 확인합니다.
7 changes: 6 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"migrate:run": "pnpm ts-node ./node_modules/typeorm/cli.js migration:run -d ./src/database/config.ts",
"migrate:revert": "pnpm ts-node ./node_modules/typeorm/cli.js migration:revert -d ./src/database/config.ts",
"migrate:reset": "pnpm migrate:revert && pnpm migrate:run",
"migrate:create": "pnpm ts-node ./node_modules/typeorm/cli.js migration:create ./src/database/migrate/custom",
"migrate:generate": "pnpm ts-node ./node_modules/typeorm/cli.js migration:generate ./src/database/migrate/auto -d ./src/database/config.ts"
},
"dependencies": {
"@anatine/zod-nestjs": "^2.0.9",
Expand Down
8 changes: 6 additions & 2 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HistoriesModule } from './histories/histories.module';
import { BooksModule } from './books/books.module';
import { dbConfig } from './config';
import { typeOrmModuleOptions } from './database/config';

@Module({
imports: [TypeOrmModule.forRoot(dbConfig), HistoriesModule, BooksModule],
imports: [
TypeOrmModule.forRoot(typeOrmModuleOptions),
HistoriesModule,
BooksModule,
],
controllers: [AppController],
providers: [AppService],
})
Expand Down
2 changes: 1 addition & 1 deletion backend/src/books/books.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
import { Book, BookCopy } from '../entities';
import { Book, BookCopy } from '../database/entities';

@Module({
imports: [TypeOrmModule.forFeature([Book, BookCopy])],
Expand Down
2 changes: 1 addition & 1 deletion backend/src/books/books.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Book, BookCopy } from '../entities';
import { Book, BookCopy } from '../database/entities';
import { PaginationOptionsDto } from '../common/dtos/page-options.dto';
import {
CreateBookCopyRequestDto,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/categories/categories.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from '../entities/Category';
import { Book } from '../entities/Book';
import { Category } from '../database/entities/Category';
import { Book } from '../database/entities/Book';
import { categoryCountSchema } from 'src/books/dto/books.dto';

@Injectable()
Expand Down
15 changes: 0 additions & 15 deletions backend/src/config.ts

This file was deleted.

23 changes: 23 additions & 0 deletions backend/src/database/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as dotenv from 'dotenv';
import { DataSource, DataSourceOptions } from 'typeorm';

dotenv.config();

export const dbConfig: DataSourceOptions = {
type: 'mysql',
host: process.env.MYSQL_HOST,
port: 3306,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
entities: [__dirname + '/entities/*{.ts,.js}'],
migrations: [__dirname + '/migrate/*{.ts,.js}'],
migrationsTableName: 'typeorm_migrations',
synchronize: false,
};

// TypeOrmModuleOptions 는 extends Partial<DataSourceOptions>
export const typeOrmModuleOptions: TypeOrmModuleOptions = dbConfig;

export const dataSource: DataSource = new DataSource(dbConfig);
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ import { Category } from './Category';
import { Likes } from './Likes';
import { Reservation } from './Reservation';
import { Reviews } from './Reviews';
import { SuperTag } from './SuperTag';
import { BookInfoSearchKeywords } from './BookInfoSearchKeywords';

@Index('categoryId', ['categoryId'], {})
@Entity('book_info')
export class Book {
@PrimaryGeneratedColumn({ type: 'int', name: 'id' })
Expand All @@ -42,13 +40,14 @@ export class Book {

@Column('datetime', {
name: 'createdAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
default: 'CURRENT_TIMESTAMP(6)',
})
createdAt: Date;

@Column('datetime', {
name: 'updatedAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
default: 'CURRENT_TIMESTAMP(6)',
onUpdate: 'CURRENT_TIMESTAMP(6)',
})
updatedAt: Date;

Expand All @@ -62,7 +61,12 @@ export class Book {
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION',
})
@JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])
@JoinColumn([
{
name: 'categoryId',
referencedColumnName: 'id',
},
])
category: Category;

@OneToMany(() => Likes, (likes) => likes.bookInfo)
Expand All @@ -74,9 +78,6 @@ export class Book {
@OneToMany(() => Reviews, (reviews) => reviews.bookInfo)
reviews?: Reviews[];

@OneToMany(() => SuperTag, (superTags) => superTags.userId)
superTags?: SuperTag[];

@OneToOne(
() => BookInfoSearchKeywords,
(bookInfoSearchKeyword) => bookInfoSearchKeyword.bookInfo,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import {
Column,
CreateDateColumn,
Entity,
Index,

Check warning on line 5 in backend/src/database/entities/BookCopy.ts

View workflow job for this annotation

GitHub Actions / autofix

'Index' is defined but never used

Check warning on line 5 in backend/src/database/entities/BookCopy.ts

View workflow job for this annotation

GitHub Actions / build (20)

'Index' is defined but never used

Check warning on line 5 in backend/src/database/entities/BookCopy.ts

View workflow job for this annotation

GitHub Actions / build (22)

'Index' is defined but never used
JoinColumn,
ManyToOne,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { Book } from './Book';
import { User } from './User';
import { Lending } from './Lending';
import { Reservation } from './Reservation';
import { BookStatus } from 'src/books/constants';

@Index('FK_donator_id_from_user', ['donatorId'], {})
@Entity('book')
export class BookCopy {
@PrimaryGeneratedColumn({ type: 'int', name: 'id' })
Expand All @@ -28,19 +29,13 @@ export class BookCopy {
@Column('int', { name: 'status' })
status: BookStatus;

@Column('datetime', {
name: 'createdAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
})
@CreateDateColumn({ name: 'createdAt' })
createdAt?: Date;

@Column('int')
infoId: number;

@Column('datetime', {
name: 'updatedAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
})
@UpdateDateColumn({ name: 'updatedAt' })
updatedAt?: Date;

@Column('int', { name: 'donatorId', nullable: true })
Expand All @@ -53,12 +48,18 @@ export class BookCopy {
@JoinColumn([{ name: 'infoId', referencedColumnName: 'id' }])
info?: Book;

@ManyToOne(() => User, (user) => user.books, {
@ManyToOne(() => User, (user) => user.donateBooks, {
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION',
})
@JoinColumn([{ name: 'donatorId', referencedColumnName: 'id' }])
donator2?: User;
@JoinColumn([
{
name: 'donatorId',
referencedColumnName: 'id',
foreignKeyConstraintName: 'FK_donator_id_from_user',
},
])
donateUser?: User;

@OneToMany(() => Lending, (lending) => lending.book)
lendings?: Lending[];
Expand Down
63 changes: 63 additions & 0 deletions backend/src/database/entities/BookInfoSearchKeywords.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import {
Column,
Entity,
JoinColumn,
OneToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { Book } from './Book';

@Entity('book_info_search_keywords')
export class BookInfoSearchKeywords {
@PrimaryGeneratedColumn({
type: 'int',
name: 'id',
})
id: number;

@Column('varchar', {
name: 'disassembled_title',
length: 255,
nullable: true,
})
disassembledTitle?: string;

@Column('varchar', {
name: 'disassembled_author',
length: 255,
nullable: true,
})
disassembledAuthor?: string;

@Column('varchar', {
name: 'disassembled_publisher',
length: 255,
nullable: true,
})
disassembledPublisher?: string;

@Column('varchar', { name: 'title_initials', length: 255, nullable: true })
titleInitials?: string;

@Column('varchar', { name: 'author_initials', length: 255, nullable: true })
authorInitials?: string;

@Column('varchar', {
name: 'publisher_initials',
length: 255,
nullable: true,
})
publisherInitials?: string;

@Column('int', { name: 'book_info_id', nullable: true })
bookInfoId?: number;

@OneToOne(() => Book, (bookInfo) => bookInfo.id)
@JoinColumn([
{
name: 'book_info_id',
referencedColumnName: 'id',
},
])
bookInfo?: Book;
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import {
Column,
CreateDateColumn,
Entity,
Index,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { BookCopy } from './BookCopy';
import { User } from './User';

@Index('FK_f2adde8c7d298210c39c500d966', ['lendingLibrarianId'], {})
@Index('FK_returningLibrarianId', ['returningLibrarianId'], {})
@Entity('lending', { schema: '42library' })
export class Lending {
@PrimaryGeneratedColumn({ type: 'int', name: 'id' })
Expand All @@ -19,7 +18,12 @@ export class Lending {
@Column('int', { name: 'lendingLibrarianId' })
lendingLibrarianId: number;

@Column('varchar', { name: 'lendingCondition', length: 255 })
@Column('varchar', {
name: 'lendingCondition',
length: 255,
nullable: false,
default: '',
})
lendingCondition: string;

@Column('int', { name: 'returningLibrarianId', nullable: true })
Expand All @@ -35,16 +39,10 @@ export class Lending {
@Column('datetime', { name: 'returnedAt', nullable: true })
returnedAt: Date | null;

@Column('timestamp', {
name: 'createdAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
})
@CreateDateColumn({ name: 'createdAt', type: 'timestamp' })
createdAt: Date;

@Column('timestamp', {
name: 'updatedAt',
default: () => "'CURRENT_TIMESTAMP(6)'",
})
@UpdateDateColumn({ name: 'updatedAt', type: 'timestamp' })
updatedAt: Date;

@ManyToOne(() => BookCopy, (book) => book.lendings, {
Expand All @@ -67,17 +65,29 @@ export class Lending {
@Column({ name: 'userId', type: 'int' })
userId: number;

@ManyToOne(() => User, (user) => user.lendings2, {
@ManyToOne(() => User, (user) => user.librarianLendings, {
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION',
})
@JoinColumn([{ name: 'lendingLibrarianId', referencedColumnName: 'id' }])
@JoinColumn([
{
name: 'lendingLibrarianId',
referencedColumnName: 'id',
foreignKeyConstraintName: 'FK_f2adde8c7d298210c39c500d966',
},
])
lendingLibrarian: User;

@ManyToOne(() => User, (user) => user.lendings3, {
@ManyToOne(() => User, (user) => user.librarianReturnings, {
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION',
})
@JoinColumn([{ name: 'returningLibrarianId', referencedColumnName: 'id' }])
@JoinColumn([
{
name: 'returningLibrarianId',
referencedColumnName: 'id',
foreignKeyConstraintName: 'FK_returningLibrarianId',
},
])
returningLibrarian: User;
}
Loading

0 comments on commit f393135

Please sign in to comment.