화면과 서버 사이의 계약
화면과 서버는 HTTP로만 이야기하므로, 무엇을 주고받는지를 둘 사이의 계약으로 정해요. 계약의 원본은 서버예요. 서버가 OpenAPI 문서를 만들고, 화면은 그 문서에서 TypeScript 타입을 생성해 써요. API를 바꾸면 계약 파일, 생성한 타입, 그 API를 부르는 화면 코드를 같은 변경에서 맞춰요.
계약을 맞추는 순서
섹션 제목: “계약을 맞추는 순서”-
서버의 컨트롤러와 요청·응답 타입(
…Requests,…Views)을 고쳐요. 서버는 springdoc으로/api/openapi에서 OpenAPI 문서를 내보내요. -
server/에서 계약 파일을 다시 써요. 이 작업은 테스트로 서버를 띄워/api/openapi를 읽고server/openapi.json에 저장해요.터미널 창 ./gradlew exportOpenApi -
web/에서 타입을 생성해요. openapi-typescript가../server/openapi.json을 읽어web/src/shared/api/schema.d.ts를 만들어요. 이 파일은 손으로 고치지 않아요.터미널 창 npm run api:generate -
web/에서npm run check를 실행해요. 화면 코드가 바뀐 계약과 맞지 않으면 타입 검사(tsc --noEmit)에서 실패해요.
화면 코드가 생성한 타입을 쓰는 방식
섹션 제목: “화면 코드가 생성한 타입을 쓰는 방식”생성한 타입은 @/shared/api가 다시 내보내요. 화면 코드는 HTTP 도우미(getJson, sendJson 등)와 타입을 이곳에서만 가져와요.
export { ApiError, getJson, isNotFound, sendCommand, sendCreate, sendJson } from './http';export type { components, } from './schema';조회를 소유한 슬라이스는 components['schemas']에서 응답 타입을 꺼내 화면에 맞게 다듬어요. 아래는 프로젝트 조회의 예예요. 서버가 늘 채워 주는 필드를 필수로 바꾸고, 서버가 판정한 can을 함께 실어요.
import { queryOptions, type QueryClient } from '@tanstack/react-query';import { getJson, sendCommand, sendCreate, type components } from '@/shared/api';
/* * Projects' reads and writes against /api/v1/workspace/projects, as client/'s. Every read sits under ['projects'], so a change * made here reads them all again. A project's key in a path is its current key or an old one, in any case. */
type Schemas = components['schemas'];type WithRequired<T, K extends keyof T> = T & { [P in K]-?: NonNullable<T[P]> };
// …
/** * A project as the screens list and open it, with its member count, whether it is the reader's favourite, and the * reader's role and what it lets them do. Only projects the reader sees are listed (their members' and every one for a * Workspace administrator). */export type Project = WithRequired<Schemas['ProjectView'], 'id' | 'key' | 'name' | 'position' | 'version' | 'memberCount' | 'favorite' | 'createdAt' | 'updatedAt'> & { myRole: ProjectRole | 'NONE'; can: ProjectCan };오류도 계약이에요
섹션 제목: “오류도 계약이에요”실패한 요청은 application/problem+json으로 돌아와요. 화면은 응답의 code로 오류를 구별하고, 업무 오류면 서버가 쓴 detail을 그대로 보여 줘요. 상태 코드와 오류 응답의 모양은 API 계약과 오류에 있어요.