MongoDB를 위한 TypeScript GraphQL 생성기 — Numio
@graphql-codegen/typescript-mongodb를 사용해 @entity, @id, @column, @link, @embedded, @map으로 주석을 단 스키마에서 TypeScript MongoDB 문서 타입을 생성합니다. @entity 타입마다 <Name>DbObject 타입이 생기며, 디렉티브가 없는 필드는 제외됩니다.
같은 엔티티의 GraphQL API 타입과 함께 MongoDB에 저장되는 문서 형태도 타입으로 관리합니다.
이럴 때 사용하세요
- 같은 엔티티의 GraphQL API 타입과 함께 MongoDB에 저장되는 문서 형태도 타입으로 관리합니다.
- 데이터 접근 코드를 작성하기 전에 @map 경로와 @link 참조가 중첩 객체와 ObjectId 배열로 어떻게 바뀌는지 확인합니다.
사용 방법
- 타입에 @entity를, 필드에 @id, @column, @link, @embedded 또는 @map(path: ...)을 사용한 스키마를 붙여 넣습니다.
- 출력 끝부분의 DbObject 타입을 확인합니다. GraphQL 타입 자체는 그 위에 생성됩니다.
- 결과를 .ts 파일에 복사합니다. mongodb 패키지에서 ObjectId를 import합니다.
MongoDB 디렉티브가 있는 GraphQL 스키마
type User @entity {
id: ID! @id
email: String! @column @map(path: "login.email")
profile: Profile! @embedded
posts: [Post!]! @link
}
type Profile @entity(embedded: true) {
name: String! @column
}
type Post @entity {
id: ID! @id
title: String! @column
}TypeScript DbObject 타입
…
export type AdditionalEntityFields = {
path?: InputMaybe<Scalars["String"]["input"]>
type?: InputMaybe<Scalars["String"]["input"]>
}
import { ObjectId } from "mongodb"
export type UserDbObject = {
_id: ObjectId
login: {
email: string
}
profile: ProfileDbObject
posts: Array<PostDbObject["_id"]>
}
export type ProfileDbObject = {
name: string
}
export type PostDbObject = {
_id: ObjectId
title: string
}세부 정보 및 제한 사항
@id는 _id: ObjectId가 되고, @link는 연결된 엔티티의 _id(리스트는 Array<PostDbObject["_id"]>)가 되며, @map(path: "login.email")은 중첩된 login 객체를 만듭니다.
디렉티브가 없는 필드(@column, @id, @link, @embedded가 없는 필드)는 DbObject 타입에 포함되지 않습니다. nullable column은 선택적 Maybe<T> 프로퍼티가 됩니다.
출력에는 표준 typescript 플러그인 타입도 포함됩니다(위 예시에서는 생략). 생성은 브라우저 Web Worker에서 실행됩니다.
FAQ
스키마에 @entity와 @column 디렉티브를 선언해야 하나요?
아니요. 플러그인이 자체 디렉티브 정의를 추가하며, 출력에 AdditionalEntityFields input 타입이 나타나는 것도 그 때문입니다.
임베디드 문서는 어떻게 타입이 지정되나요?
@entity(embedded: true)로 선언한 타입은 _id가 없는 DbObject 타입을 얻고, @embedded가 붙은 필드가 이를 참조합니다. 예: profile: ProfileDbObject.
DbObject 타입에 필드가 빠진 이유는 무엇인가요?
@id, @column, @link, @embedded 또는 @map이 있는 필드만 저장 필드입니다. 일반 필드를 포함하려면 @column을 추가하세요.