Dynamo DB, dynamoose & Nestjs

Jina Kim·2023년 3월 8일
1

AWS

목록 보기
2/2
post-thumbnail

Dynamo DB + NestJS 한글 버젼이 없어서 남김
(앗싸 조회수🔺)

Dynamo DB

Dynamo DB는 AWS의 대표적인 NoSQL 기반 데이터베이스이다.
NoSQL은 정형화된 데이터를 저장하는 RDB와는 다르게 비정형 데이터를 처리한다.

NoSQL의 특징

  1. key-value로 저장
  2. 정해진 스키마가 없어서 변경이 자유로움
  3. 대용량 데이터 처리를 빠른 질의 속도로 지원
  4. 대표적으로는 카산드라, mongoDB가 있음

table

  • 아이템들이 들어있는 곳
  • 아이템 개수 제한 없음
  • 파티션 키(기본키)를 정해줘야 함

item

  • attribute들이 들어있는 곳
  • attribute 개수 제한 없음

attribute

  • key-value 형식.key는 문자열

Nestjs에 dynamoDB 연결하기

dynamoose 패키지를 설치한다.
https://www.npmjs.com/package/nestjs-dynamoose

npm install --save nestjs-dynamoose dynamoose

Dynamoose 모듈을 app.module에 추가하여 Dynamo DB를 연결한다.
config 정보는 따로 파일로 만들었다.
// app.module.ts
import { DynamooseModule } from 'nestjs-dynamoose';
import { DynamooseConfigService } from './dynamoose-config.service';

@Module({
 imports: [
   DynamooseModule.forRootAsync({ useClass: DynamooseConfigService }),
   ....
 ],
})
export class AppModule {}
// dynamoose-config.service.ts
import {
  DynamooseOptionsFactory,
  DynamooseModuleOptions,
} from 'nestjs-dynamoose';

export class DynamooseConfigService implements DynamooseOptionsFactory {
  createDynamooseOptions(): DynamooseModuleOptions {
    return {
      aws: {
        // .env에 선언해야 보안상 좋음
        accessKeyId: AWS 액세스 키,
        secretAccessKey: AWS 시크릿 액세스 키, // 처음 액세스 키 만들 때 말고는 aws-cli로 쳐서 따로 봐야 하니 기록해둘 것
        region: 리젼,
      },
    };
  }
}

interface, schema를 작성한다.
// user-info.interface.ts
export interface UserInfoKey {
  user_id: string; // hashKey(파티션 키)
  user_idx: number; // rangeKey(정렬 키)
}

export interface User extends UserInfoKey {
  user_email?: string;
}
// user-info.schema.ts

import { Schema } from 'dynamoose';

export const UserInfoSchema = new Schema(
  {
    user_id: {
      type: String,
      hashKey: true,
      required: true,
    },
    user_idx: {
      type: Number,
      rangeKey: true,
    },
    user_email: {
      type: String,
    },
  },
  {
    timestamps: true, // createdAt, updateAt 컬럼
    
    /* 이렇게 쓸 수도 있음
    timestamps: {
     * 		"createdAt": "createDate",
     * 		"updatedAt": null // updatedAt will not be stored as part of the timestamp
     * 	}
    */
  },
);


module에 사용할 table, schema를 추가한다.

// user.module.ts.
import { DynamooseModule } from 'nestjs-dynamoose';
import { UserInfoSchema } from './schema/user-info.schema';
...

@Module({
  imports: [
     DynamooseModule.forFeature([
      { name: 'UserInfo', schema: UserInfoSchema },
    ]),
    ...
  ],
  controllers: [UserController],
  providers: [
    UserService,
    ...
  ],
});
export class UserModule {}


controller, service를 작성한다.

// user.controller.ts
@Post('/user/:user_id')
saveUserInfo(
  @Param('user_id') user_id: string,
  @Body('user_idx') user_idx: number,
  @Body('user_email') user_email: string,
) {
  return this.userService.saveUserInfo(
    user_id,
    user_idx,
    user_email,
  );
}
// user.service.ts
import { InjectModel, Model } from 'nestjs-dynamoose';
import {
  UserInfo,
  UserInfoKey,
} from './interfaces/user-info.interface';

export class UserService {
  constructor(
    @InjectModel('UserInfo')
    private userInfoModel: Model<UserInfo, UserInfoKey>,
  ) {}

  async saveUserInfo(
    user_id: string,
    user_idx: number,
    user_email: string,
  ) {
    const userData = {
      user_id,
      user_idx,
      user_email,
    };
    return this.userInfoModel.create(userData);
  }
}

CRUD 예시

constructor model 생성

@InjectModel('UserInfo')
private userInfoModel: Model<UserInfo, UserInfoKey>,

create

const userData = {
  user_id,// 파티션 키
  user_idx,// 정렬 키
  user_email, // 데이터
};
this.userInfoModel.create(userData);

read

// 파티션 키, 정렬 키(있다면) 둘다 써줘야함
this.userInfoModel.get({ user_id, user_idx }); 

update

this.userInfoModel.update(userData);

delete

this.userInfoModel.delete({ user_id, user_idx });

데이터 insert된거 확인하려면 https://tttap.tistory.com/175 여기 보면 될 듯~

빠른 정리 끝!

profile
Hello, World!

1개의 댓글

comment-user-thumbnail
2024년 1월 16일

다이나모 DB에서 테이블은 생성하고 데이터를 집어넣어야 하나봅니다.
스키마를 코드로 미리 작성하고 테이블이 없는 상태에서 데이터를 넣을 시는 에러가 발생하네용ㅋㅋ

답글 달기