Scalars

Scalars

GraphQL์—๋Š” Int, Float, String, Boolean ๋ฐ ID์™€ ๊ฐ™์€ ๊ธฐ๋ณธ ์œ ํ˜•์ด ํฌํ•จ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๋•Œ๋•Œ๋กœ ์‚ฌ์šฉ์ž ์ •์˜ ์›์ž ๋ฐ์ดํ„ฐ ์œ ํ˜• (์˜ˆ: ๋‚ ์งœ)์„ ์ง€์›ํ•ด์•ผ ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

Schema first

์‚ฌ์šฉ์ž ์ง€์ • ์Šค์นผ๋ผ๋ฅผ ์ •์˜ํ•˜๋ ค๋ฉด (์Šค์นผ๋ผ์— ๋Œ€ํ•œ ์ž์„ธํ•œ ๋‚ด์šฉ์€ ์—ฌ๊ธฐ) ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ˜•์‹ ์ •์˜์™€ ์ „์šฉ ๋ฆฌ์กธ๋ฒ„๋ฅผ ๋งŒ๋“ค์–ด์•ผํ•ฉ๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ๋Š” ๊ณต์‹ ๋ฌธ์„œ์—์„œ์™€ ๊ฐ™์ด ๋ฐ๋ชจ ๋ชฉ์ ์œผ๋กœ graphql-type-json ํŒจํ‚ค์ง€๋ฅผ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค. ์ด npm ํŒจํ‚ค์ง€๋Š” JSON GraphQL ์Šค์นผ๋ผ ์œ ํ˜•์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ๋จผ์ € ํŒจํ‚ค์ง€๋ฅผ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค:

$ npm i --save graphql-type-json

ํŒจํ‚ค์ง€๊ฐ€ ์„ค์น˜๋˜๋ฉด ์ปค์Šคํ…€ ๋ฆฌ์กธ๋ฒ„๋ฅผ forRoot()๋ฉ”์†Œ๋“œ์— ์ „๋‹ฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค :

import * as GraphQLJSON from 'graphql-type-json';

@Module({
  imports: [
    GraphQLModule.forRoot({
      typePaths: ['./**/*.graphql'],
      resolvers: { JSON: GraphQLJSON },
    }),
  ],
})
export class ApplicationModule {}

์ด์ œ ํƒ€์ž… ์ •์˜์— JSON ์Šค์นผ๋ผ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค :

scalar JSON

type Foo {
  field: JSON
}

์Šค์นผ๋ผ ํ˜•์‹์„ ์ •์˜ํ•˜๋Š” ๋˜ ๋‹ค๋ฅธ ํ˜•ํƒœ๋Š” ๊ฐ„๋‹จํ•œ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. Date ์œ ํ˜•์œผ๋กœ ์Šคํ‚ค๋งˆ๋ฅผ ํ–ฅ์ƒ์‹œํ‚ค๊ณ  ์‹ถ๋‹ค๊ณ  ๊ฐ€์ • ํ•ด ๋ด…์‹œ๋‹ค.

import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';

@Scalar('Date')
export class DateScalar implements CustomScalar<number, Date> {
  description = 'Date custom scalar type';

  parseValue(value: number): Date {
    return new Date(value); // value from the client
  }

  serialize(value: Date): number {
    return value.getTime(); // value sent to the client
  }

  parseLiteral(ast: ValueNode): Date {
    if (ast.kind === Kind.INT) {
      return new Date(ast.value);
    }
    return null;
  }
}

์ดํ›„, ๊ณต๊ธ‰์ž๋กœ DateScalar๋ฅผ ๋“ฑ๋กํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

@Module({
  providers: [DateScalar],
})
export class CommonModule {}

์ด์ œ ํƒ€์ž… ์ •์˜์— Date ์Šค์นผ๋ผ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

scalar Date

Code first

๋‚ ์งœ ์Šค์นผ๋ผ๋ฅผ ๋งŒ๋“ค๋ ค๋ฉด ๊ฐ„๋‹จํžˆ ์ƒˆ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ์‹ญ์‹œ์˜ค.

import { Scalar, CustomScalar } from '@nestjs/graphql';
import { Kind, ValueNode } from 'graphql';

@Scalar('Date', type => Date)
export class DateScalar implements CustomScalar<number, Date> {
  description = 'Date custom scalar type';

  parseValue(value: number): Date {
    return new Date(value); // value from the client
  }

  serialize(value: Date): number {
    return value.getTime(); // value sent to the client
  }

  parseLiteral(ast: ValueNode): Date {
    if (ast.kind === Kind.INT) {
      return new Date(ast.value);
    }
    return null;
  }
}

์ค€๋น„๊ฐ€๋˜๋ฉด DateScalar๋ฅผ ๊ณต๊ธ‰์ž๋กœ ๋“ฑ๋กํ•˜์‹ญ์‹œ์˜ค.

@Module({
  providers: [DateScalar],
})
export class CommonModule {}

์ด์ œ ํด๋ž˜์Šค์—์„œ ๋‚ ์งœ ์œ ํ˜•์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

@Field()
creationDate: Date;

Last updated

Was this helpful?