티스토리 뷰
728x90
출처
- Providers | NestJS - A progressive Node.js framework
- NestJs 데이터베이스 연동하기 (mysql, typeorm) : 호두의 개발스토리
Entity 객체
Entity 부모 클래스 ( node_modules\typeorm\decorator\entity\Entity.d.ts )
import { EntityOptions } from "../options/EntityOptions";
/**
* This decorator is used to mark classes that will be an entity (table or document depend on database type).
* Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
*/
export declare function Entity(options?: EntityOptions): ClassDecorator;
/**
* This decorator is used to mark classes that will be an entity (table or document depend on database type).
* Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
*/
export declare function Entity(name?: string, options?: EntityOptions): ClassDecorator;
User 클래스 ( entities/user.entity.ts )
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn} from 'typeorm';
@Entity({ name: 'users' })
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column()
public roleId: number;
@Column()
public avatarId: number;
@Column()
public nickname: string;
@Column()
public email: string;
@Column()
public phone: string;
@Column()
public phoneWithCountryCode: string;
@Column()
public bio: string;
}
Service 클래스 ( user.service.ts )
Controller에서 요청 받은 내용을 Service 객체를 통해서 데이터 저장 및 검색한 결과를 반환
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private readonly _usersRepository: Repository<User>,
) { }
public async detailUser(id: number): Promise<any> {
const queryBuilder = this._usersRepository.createQueryBuilder('users');
queryBuilder.where('users.id = :userId', { userId: id });
const user = await queryBuilder.getOne();
return user;
}
}
Controller 클래스 ( user.controller.ts )
Controller는 http 요청을 처리 하고 클라이언트에 응답을 반환하는 하는 클래스
import { Controller, Get, Param } from '@nestjs/common';
import { User } from './entities/user.entity';
import { UsersService } from './user.service';
@Controller()
export class UsersController {
constructor(
private readonly _userService: UsersService
) { }
@Get('detail/:id')
public async findOne(@Param('id') id : number) {
return this._userService.detailUser(id);
}
}
Module 클래스 ( user.module.ts )
Module 데코레이터가 붙어있는 클래스로 Nest가 전체 어플리케이션의 구조를 정의한 메타데이터 제공
- providers : Service 클래스
- controllers : Controller 클래스
- imports :
- exports :
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './user.controller';
import { User } from './entities/user.entity';
import { UsersService } from './user.service';
@Module({
imports: [ TypeOrmModule.forFeature([ User ]), ],
controllers: [ UsersController ],
providers: [ UsersService ],
})
export class UsersModule {
}
메인 Module 클래스 ( app.module.ts )
imports에 UsersModule 추가
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { configValidationSchema } from 'config/validation/config-validation';
import databaseConfig from '../config/database.config';
import { UsersModule } from './v1/users/user.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
cache: true,
envFilePath: [ '.env.' + process.env.NODE_ENV ],
ignoreEnvFile: process.env.NODE_ENV === 'prod',
validationSchema: configValidationSchema,
load: [ databaseConfig ],
}),
TypeOrmModule.forRootAsync({
imports: [ ConfigModule ],
useFactory: (configService: ConfigService) =>
configService.get('database'),
inject: [ ConfigService ],
}),
UsersModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
실행
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- ubuntu
- 일본여행
- Java
- oracle
- flex
- 지스타2007
- 서울오토살롱
- KOBA
- Delphi Tip
- ffmpeg
- sas2009
- 송주경
- 레이싱모델 익스트림 포토 페스티벌
- ble
- koba2010
- JavaScript
- Delphi
- Linux
- 튜닝쇼 2008
- android
- Mac
- Xcode
- 동경
- SAS
- Spring
- BPI-M4
- MySQL
- Spring MVC
- NDK
- 전예희
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함