Adds comprehensive page management and temporary access tokens

Introduces the `PageModule` to provide full CRUD capabilities for pages within spaces.

Key features include:
-   API endpoints for creating, retrieving, updating, and soft-deleting pages.
-   Support for hierarchical page structures with validation to prevent circular references.
-   A mechanism to generate and manage temporary access tokens, allowing controlled public access to specific pages or entire spaces.
-   Integration with database repositories and comprehensive Swagger documentation for all new endpoints and DTOs.
-   Ensures proper authorization and validation for all page and token operations.
This commit is contained in:
dahyeon committed 2025-11-10 15:42:02 +00:00
1 parent ef440a2dbd
commit bb992167d2
10 files changed
+2315 -5

No files matched your search

+382
View File
@@ -0,0 +1,382 @@
# Kiota API Client 생성 가이드
이 문서는 Swagger/OpenAPI 스펙으로부터 Kiota를 사용하여 타입 안전한 API 클라이언트를 생성하는 방법을 설명합니다.
## Swagger 문서 접근
서버가 개발 또는 테스트 모드로 실행 중일 때:
- **Swagger UI**: `http://localhost:3415/v1/api` (UI는 비활성화됨)
- **OpenAPI YAML**: `http://localhost:3415/v1/api-yaml`
- **OpenAPI JSON**: `http://localhost:3415/v1/api-json`
## Kiota 설치
```bash
# .NET 도구로 설치
dotnet tool install --global Microsoft.OpenApi.Kiota
# 또는 npm으로 설치
npm install -g @microsoft/kiota
```
## API 클라이언트 생성
### 1. OpenAPI 스펙 다운로드
서버를 실행한 후:
```bash
# YAML 형식으로 다운로드 (권장)
curl http://localhost:3415/v1/api-yaml > openapi.yaml
# 또는 JSON 형식
curl http://localhost:3415/v1/api-json > openapi.json
```
### 2. Kiota로 클라이언트 생성
#### TypeScript/JavaScript 클라이언트
```bash
kiota generate \
-l typescript \
-d openapi.yaml \
-c WikiApiClient \
-o ./generated/typescript \
--exclude-backward-compatible
```
#### C# 클라이언트
```bash
kiota generate \
-l csharp \
-d openapi.yaml \
-c WikiApiClient \
-n WikiApi.Client \
-o ./generated/csharp
```
#### Java 클라이언트
```bash
kiota generate \
-l java \
-d openapi.yaml \
-c WikiApiClient \
-n com.wiki.client \
-o ./generated/java
```
#### Python 클라이언트
```bash
kiota generate \
-l python \
-d openapi.yaml \
-c WikiApiClient \
-n wiki_api_client \
-o ./generated/python
```
## API 엔드포인트 구조
생성된 클라이언트는 다음 엔드포인트를 포함합니다:
### Space API (`/v1/space`)
모든 엔드포인트는 `@ApiTags('Space')` 태그로 그룹화됩니다.
#### 1. POST /v1/space - 스페이스 생성
- **Request**: `CreateSpaceDto`
- `spaceKey` (string, required, pattern: ^[a-z0-9-]+$, max 50)
- `name` (string, required, max 255)
- `description` (string, optional)
- `userId` (uuid, required)
- **Response**: `SpaceResponseDto`
#### 2. GET /v1/space - 모든 스페이스 조회
- **Query Parameters**:
- `withCreator` (boolean, optional) - 생성자 정보 포함 여부
- **Response**: `SpaceResponseDto[]` 또는 `SpaceWithCreatorDto[]`
#### 3. GET /v1/space/{spaceId} - 스페이스 ID로 조회
- **Path Parameter**: `spaceId` (uuid)
- **Query Parameters**:
- `withCreator` (boolean, optional)
- **Response**: `SpaceResponseDto` 또는 `SpaceWithCreatorDto`
#### 4. GET /v1/space/key/{spaceKey} - 스페이스 키로 조회
- **Path Parameter**: `spaceKey` (string)
- **Response**: `SpaceResponseDto`
#### 5. GET /v1/space/{spaceId}/statistics - 스페이스 통계
- **Path Parameter**: `spaceId` (uuid)
- **Response**: `SpaceStatisticsDto`
#### 6. GET /v1/space/user/{userId} - 사용자의 스페이스 목록
- **Path Parameter**: `userId` (uuid)
- **Response**: `SpaceResponseDto[]`
#### 7. PUT /v1/space/{spaceId} - 스페이스 업데이트
- **Path Parameter**: `spaceId` (uuid)
- **Request**: `UpdateSpaceDto`
- `name` (string, optional)
- `description` (string, optional)
- **Response**: `SpaceResponseDto`
#### 8. DELETE /v1/space/{spaceId} - 스페이스 삭제
- **Path Parameter**: `spaceId` (uuid)
- **Response**: `DeleteSpaceResponseDto`
- **Warning**: CASCADE로 모든 페이지도 삭제됨
---
### Page API (`/v1/page`)
모든 엔드포인트는 `@ApiTags('Page')` 태그로 그룹화됩니다.
#### 1. POST /v1/page - 페이지 생성
- **Request**: `CreatePageDto`
- `spaceId` (uuid, required)
- `parentPageId` (uuid, optional)
- `title` (string, required, max 255)
- `content` (string, optional)
- `userId` (uuid, required)
- `sortOrder` (number, optional, default: 0)
- **Response**: `PageResponseDto`
#### 2. GET /v1/page - 페이지 조회
- **Query Parameters**:
- `pageId` (uuid, optional) - 특정 페이지 조회
- `spaceId` (uuid, optional) - 스페이스의 모든 페이지 조회
- **Response**: `PageResponseDto` 또는 `PageResponseDto[]`
#### 3. PUT /v1/page/{pageId} - 페이지 업데이트
- **Path Parameter**: `pageId` (uuid)
- **Request**: `UpdatePageDto`
- `title` (string, optional)
- `content` (string, optional)
- `parentPageId` (uuid, optional, nullable)
- `sortOrder` (number, optional)
- `userId` (uuid, required)
- **Response**: `PageResponseDto`
#### 4. DELETE /v1/page/{pageId} - 페이지 삭제
- **Path Parameter**: `pageId` (uuid)
- **Request**: `DeletePageDto`
- `userId` (uuid, required)
- **Response**: `DeleteResponseDto`
#### 5. POST /v1/page/temporary-access-token - 토큰 생성
- **Request**: `CreateTemporaryTokenDto`
- `pageIds` (uuid[], optional) - 권한을 부여할 페이지 ID 배열
- `spaceIds` (uuid[], optional) - 권한을 부여할 스페이스 ID 배열
- `expiresInHours` (number, optional, min: 1)
- `description` (string, optional, max 255)
- `userId` (uuid, required)
- **Response**: `CreateTokenResponseDto`
- `token`: `TokenInfoDto`
- `permissions`: `TokenPermissionsDto`
#### 6. DELETE /v1/page/temporary-access-token - 토큰 삭제
- **Request**: `DeleteTokenDto`
- `tokenValue` (string, required)
- `userId` (uuid, required)
- **Response**: `DeleteResponseDto`
## 사용 예제
### TypeScript 클라이언트 사용
```typescript
import { WikiApiClient } from './generated/typescript';
import { FetchRequestAdapter } from '@microsoft/kiota-http-fetchlibrary';
// 클라이언트 초기화
const adapter = new FetchRequestAdapter();
adapter.baseUrl = 'http://localhost:3415/v1';
const client = new WikiApiClient(adapter);
// 스페이스 생성
const newSpace = await client.space.post({
spaceKey: 'engineering',
name: 'Engineering Team',
description: 'Engineering documentation',
userId: '550e8400-e29b-41d4-a716-446655440001'
});
// 스페이스 조회 (키로)
const space = await client.space.key.bySpaceKey('engineering').get();
// 모든 스페이스 조회 (생성자 정보 포함)
const allSpaces = await client.space.get({
queryParameters: {
withCreator: true
}
});
// 페이지 생성
const newPage = await client.page.post({
spaceId: newSpace.spaceId,
title: 'My New Page',
content: '# Welcome\n\nThis is my page.',
userId: '550e8400-e29b-41d4-a716-446655440001'
});
// 페이지 조회
const page = await client.page.get({
queryParameters: {
pageId: newPage.pageId
}
});
// 페이지 업데이트
const updatedPage = await client.page.byPageId(newPage.pageId).put({
title: 'Updated Title',
content: '# Updated\n\nNew content.',
userId: '550e8400-e29b-41d4-a716-446655440001'
});
// 임시 토큰 생성
const tokenResponse = await client.page.temporaryAccessToken.post({
pageIds: [newPage.pageId],
expiresInHours: 24,
description: '24시간 공유 링크',
userId: '550e8400-e29b-41d4-a716-446655440001'
});
console.log('Token:', tokenResponse.token.tokenValue);
// 토큰 삭제
await client.page.temporaryAccessToken.delete({
tokenValue: tokenResponse.token.tokenValue,
userId: '550e8400-e29b-41d4-a716-446655440001'
});
// 페이지 삭제
await client.page.byPageId(newPage.pageId).delete({
userId: '550e8400-e29b-41d4-a716-446655440001'
});
```
### C# 클라이언트 사용
```csharp
using WikiApi.Client;
using Microsoft.Kiota.Http.HttpClientLibrary;
// 클라이언트 초기화
var adapter = new HttpClientRequestAdapter(authProvider);
adapter.BaseUrl = "http://localhost:3415/v1";
var client = new WikiApiClient(adapter);
// 스페이스 생성
var newSpace = await client.Space.PostAsync(new CreateSpaceDto
{
SpaceKey = "engineering",
Name = "Engineering Team",
Description = "Engineering documentation",
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
// 스페이스 조회 (키로)
var space = await client.Space.Key["engineering"].GetAsync();
// 스페이스 통계 조회
var statistics = await client.Space[newSpace.SpaceId].Statistics.GetAsync();
// 페이지 생성
var newPage = await client.Page.PostAsync(new CreatePageDto
{
SpaceId = newSpace.SpaceId,
Title = "My New Page",
Content = "# Welcome\n\nThis is my page.",
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
// 페이지 조회
var page = await client.Page.GetAsync(config =>
{
config.QueryParameters.PageId = newPage.PageId;
});
// 페이지 업데이트
var updatedPage = await client.Page[newPage.PageId].PutAsync(new UpdatePageDto
{
Title = "Updated Title",
Content = "# Updated\n\nNew content.",
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
// 임시 토큰 생성
var tokenResponse = await client.Page.TemporaryAccessToken.PostAsync(new CreateTemporaryTokenDto
{
PageIds = new[] { newPage.PageId },
ExpiresInHours = 24,
Description = "24시간 공유 링크",
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
Console.WriteLine($"Token: {tokenResponse.Token.TokenValue}");
// 토큰 삭제
await client.Page.TemporaryAccessToken.DeleteAsync(new DeleteTokenDto
{
TokenValue = tokenResponse.Token.TokenValue,
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
// 페이지 삭제
await client.Page[newPage.PageId].DeleteAsync(new DeletePageDto
{
UserId = "550e8400-e29b-41d4-a716-446655440001"
});
```
## 타입 안전성
Kiota로 생성된 클라이언트는 완전한 타입 안전성을 제공합니다:
- ✅ 모든 DTO에 대한 타입 정의
- ✅ UUID 형식 검증
- ✅ 필수/선택 필드 구분
- ✅ 배열 타입 지원
- ✅ Nullable 타입 지원
- ✅ 에러 응답 타입 정의
- ✅ 자동 완성 지원
## 주요 특징
### 1. 토큰 권한 모델
토큰은 여러 페이지와 스페이스에 대한 권한을 배열로 가질 수 있습니다:
- `pageIds`: 특정 페이지들에 대한 직접 접근 권한
- `spaceIds`: 스페이스 내 모든 페이지에 대한 접근 권한
### 2. 계층 구조
페이지는 부모-자식 관계를 가질 수 있으며, 순환 참조가 자동으로 방지됩니다.
### 3. 소프트 삭제
페이지 삭제는 소프트 삭제로 처리되어 복구가 가능합니다.
## 문제 해결
### OpenAPI 스펙이 다운로드되지 않는 경우
- 서버가 `dev` 또는 `test` 모드로 실행 중인지 확인
- `NODE_ENV` 환경 변수 확인
### Kiota 생성 오류
- OpenAPI 스펙이 유효한지 확인: https://editor.swagger.io/
- Kiota 버전 확인: `kiota --version`
- 최신 버전으로 업데이트: `dotnet tool update --global Microsoft.OpenApi.Kiota`
### 타입 불일치 오류
- 서버와 클라이언트의 OpenAPI 스펙 버전이 일치하는지 확인
- 클라이언트를 재생성
## 추가 리소스
- [Kiota 공식 문서](https://learn.microsoft.com/en-us/openapi/kiota/)
- [OpenAPI 스펙](https://swagger.io/specification/)
- [NestJS Swagger](https://docs.nestjs.com/openapi/introduction)
+5 -1
View File
@@ -5,6 +5,8 @@ import { GlobalModule } from './modules/global/global.module';
import { ConfigModule } from '@nestjs/config';
import { AccountModule } from './modules/account/account.module';
import { ImageModule } from './modules/image/image.module';
import { PageModule } from './modules/page/page.module';
import { SpaceModule } from './modules/space/space.module';
@Module({
imports: [
@@ -14,7 +16,9 @@ import { ImageModule } from './modules/image/image.module';
}),
GlobalModule,
AccountModule,
ImageModule
ImageModule,
PageModule,
SpaceModule
],
controllers: [AppController],
providers: [AppService],
+316
View File
@@ -0,0 +1,316 @@
# Page API Documentation
## Endpoints
### 1. POST /page
페이지를 생성합니다.
**Request Body:**
```json
{
"spaceId": "uuid",
"parentPageId": "uuid (optional)",
"title": "페이지 제목",
"content": "페이지 내용 (optional)",
"userId": "uuid",
"sortOrder": 0
}
```
**Response:**
```json
{
"pageId": "uuid",
"spaceId": "uuid",
"parentPageId": "uuid or null",
"sortOrder": 0,
"title": "페이지 제목",
"content": "페이지 내용",
"createdByUserId": "uuid",
"updatedByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z",
"isDeleted": false
}
```
**Validations:**
- `spaceId`는 존재하는 스페이스여야 함
- `parentPageId`가 제공된 경우, 같은 스페이스 내에 존재해야 함
---
### 2. GET /page
페이지를 조회합니다. `pageId` 또는 `spaceId` 중 하나를 제공해야 합니다.
**Query Parameters:**
- `pageId` (optional): 특정 페이지 ID
- `spaceId` (optional): 스페이스 ID (해당 스페이스의 모든 페이지 반환)
**Examples:**
특정 페이지 조회:
```
GET /page?pageId=uuid
```
스페이스의 모든 페이지 조회:
```
GET /page?spaceId=uuid
```
**Response (단일 페이지):**
```json
{
"pageId": "uuid",
"spaceId": "uuid",
"parentPageId": "uuid or null",
"sortOrder": 0,
"title": "페이지 제목",
"content": "페이지 내용",
"createdByUserId": "uuid",
"updatedByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z",
"isDeleted": false
}
```
**Response (여러 페이지):**
```json
[
{
"pageId": "uuid",
"spaceId": "uuid",
...
},
...
]
```
---
### 3. PUT /page/:pageId
페이지를 업데이트합니다.
**URL Parameters:**
- `pageId`: 업데이트할 페이지 ID
**Request Body:**
```json
{
"title": "새 제목 (optional)",
"content": "새 내용 (optional)",
"parentPageId": "uuid or null (optional)",
"sortOrder": 1,
"userId": "uuid"
}
```
**Response:**
```json
{
"pageId": "uuid",
"spaceId": "uuid",
"parentPageId": "uuid or null",
"sortOrder": 1,
"title": "새 제목",
"content": "새 내용",
"createdByUserId": "uuid",
"updatedByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z",
"isDeleted": false
}
```
**Validations:**
- 페이지는 자기 자신을 부모로 설정할 수 없음
- 부모 페이지는 같은 스페이스 내에 있어야 함
- 순환 참조 방지 (자손을 부모로 설정할 수 없음)
---
### 4. DELETE /page/:pageId
페이지를 소프트 삭제합니다 (`isDeleted` 플래그를 true로 설정).
**URL Parameters:**
- `pageId`: 삭제할 페이지 ID
**Request Body:**
```json
{
"userId": "uuid"
}
```
**Response:**
```json
{
"message": "Page deleted successfully",
"pageId": "uuid"
}
```
---
### 5. POST /page/temporary-access-token
임시 액세스 토큰을 생성합니다. 토큰은 특정 페이지 또는 스페이스에 대한 접근 권한을 가집니다.
**Request Body:**
```json
{
"pageIds": ["uuid1", "uuid2"],
"spaceIds": ["uuid3", "uuid4"],
"expiresInHours": 24,
"description": "토큰 설명 (optional)",
"userId": "uuid"
}
```
**Notes:**
- `pageIds`와 `spaceIds` 중 최소 하나는 제공되어야 함
- `expiresInHours`를 생략하면 만료되지 않는 토큰 생성
- 토큰은 안전한 랜덤 문자열로 생성됨 (base64url 인코딩)
**Response:**
```json
{
"token": {
"tokenId": "uuid",
"tokenValue": "random-secure-token-string",
"description": "토큰 설명",
"expiresAt": "2024-01-02T00:00:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z"
},
"permissions": {
"pageIds": ["uuid1", "uuid2"],
"spaceIds": ["uuid3", "uuid4"]
}
}
```
**Use Case:**
외부 사용자나 시스템에게 특정 페이지/스페이스에 대한 임시 접근 권한을 부여할 때 사용합니다.
---
### 6. DELETE /page/temporary-access-token
임시 액세스 토큰을 삭제합니다.
**Request Body:**
```json
{
"tokenValue": "token-string",
"userId": "uuid"
}
```
**Response:**
```json
{
"message": "Token deleted successfully",
"tokenId": "uuid"
}
```
**Validations:**
- 토큰 생성자만 삭제 가능
- 존재하지 않는 토큰 삭제 시 404 에러
---
## Error Responses
모든 엔드포인트는 다음과 같은 에러 응답을 반환할 수 있습니다:
### 400 Bad Request
```json
{
"statusCode": 400,
"message": "Error message",
"error": "Bad Request"
}
```
### 401 Unauthorized
```json
{
"statusCode": 401,
"message": "You can only delete tokens you created",
"error": "Unauthorized"
}
```
### 404 Not Found
```json
{
"statusCode": 404,
"message": "Page with id 'uuid' not found",
"error": "Not Found"
}
```
---
## Token Permission Model
토큰 권한은 다음과 같이 동작합니다:
1. **페이지 권한**: 특정 페이지에 대한 직접 접근 권한
2. **스페이스 권한**: 스페이스 내 모든 페이지에 대한 접근 권한
### 데이터베이스 제약사항
- 각 권한은 `spaceId` 또는 `pageId` 중 정확히 하나만 가져야 함
- 토큰-스페이스 조합은 유니크해야 함
- 토큰-페이지 조합은 유니크해야 함
- 토큰 삭제 시 관련 권한도 cascade로 삭제됨
### 권한 확인 로직
페이지 접근 시:
1. 해당 페이지에 대한 직접 권한이 있는지 확인
2. 없다면, 페이지가 속한 스페이스에 대한 권한이 있는지 확인
---
## Example Usage
### 페이지 생성 및 토큰 발급 플로우
```bash
# 1. 페이지 생성
curl -X POST http://localhost:3000/page \
-H "Content-Type: application/json" \
-d '{
"spaceId": "space-uuid",
"title": "My Page",
"content": "Page content",
"userId": "user-uuid"
}'
# Response: { "pageId": "new-page-uuid", ... }
# 2. 해당 페이지에 대한 임시 토큰 생성
curl -X POST http://localhost:3000/page/temporary-access-token \
-H "Content-Type: application/json" \
-d '{
"pageIds": ["new-page-uuid"],
"expiresInHours": 24,
"description": "24시간 공유 링크",
"userId": "user-uuid"
}'
# Response: { "token": { "tokenValue": "abc123...", ... }, ... }
# 3. 토큰을 사용하여 페이지 조회 (인증 미들웨어에서 처리)
curl -X GET http://localhost:3000/page?pageId=new-page-uuid \
-H "Authorization: Bearer abc123..."
# 4. 토큰 삭제
curl -X DELETE http://localhost:3000/page/temporary-access-token \
-H "Content-Type: application/json" \
-d '{
"tokenValue": "abc123...",
"userId": "user-uuid"
}'
```
+208 -2
View File
@@ -1,7 +1,213 @@
import { Controller } from "@nestjs/common";
import { PageService } from "./page.service";
import { Controller, Post, Get, Put, Delete, Body, Query, Param, HttpCode, HttpStatus, UseGuards } from "@nestjs/common";
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiParam,
ApiQuery,
ApiBadRequestResponse,
ApiNotFoundResponse,
ApiUnauthorizedResponse,
ApiBearerAuth
} from "@nestjs/swagger";
import {
PageService,
CreatePageDto,
UpdatePageDto,
GetPageQuery,
CreateTemporaryTokenDto,
DeletePageDto,
DeleteTokenDto,
PageResponseDto,
CreateTokenResponseDto,
DeleteResponseDto
} from "./page.service";
import { AllowPublicAccess } from "../global/auth/allow-public-access.decorator";
import { ExtractUserPayloadFromToken } from "../global/auth/extract-user-payload-from-token.decorator";
import { type EntraIDPayloadClaims } from "../global/auth/jwt.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
@ApiTags('Page')
@UseGuards(JwtAuthGuard)
@Controller('page')
export class PageController {
constructor(private readonly pageService: PageService) {}
/**
* POST /page - 페이지 생성
*/
@Post()
@ApiBearerAuth()
@ApiOperation({
summary: '페이지 생성',
description: '새로운 페이지를 생성합니다. 스페이스 내에서 계층 구조를 가질 수 있습니다. (인증 필요)'
})
@ApiResponse({
status: 201,
description: '페이지가 성공적으로 생성됨',
type: PageResponseDto
})
@ApiBadRequestResponse({ description: '잘못된 요청 (부모 페이지가 다른 스페이스에 있음 등)' })
@ApiNotFoundResponse({ description: '스페이스 또는 부모 페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async createPage(
@Body() dto: Omit<CreatePageDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<PageResponseDto> {
return await this.pageService.createPage({
...dto,
userId: user.oid
}) as any;
}
/**
* GET /page - 페이지 조회
* Query params: pageId 또는 spaceId
*/
@Get()
@AllowPublicAccess()
@ApiOperation({
summary: '페이지 조회',
description: 'pageId로 특정 페이지를 조회하거나, spaceId로 스페이스의 모든 페이지를 조회합니다. (공개 접근 가능)'
})
@ApiQuery({
name: 'pageId',
required: false,
description: '조회할 페이지 ID',
type: String,
format: 'uuid'
})
@ApiQuery({
name: 'spaceId',
required: false,
description: '조회할 스페이스 ID (해당 스페이스의 모든 페이지 반환)',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '페이지 조회 성공',
type: PageResponseDto,
isArray: true
})
@ApiBadRequestResponse({ description: 'pageId 또는 spaceId 중 하나는 필수' })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음' })
async getPage(@Query() query: GetPageQuery): Promise<PageResponseDto | PageResponseDto[]> {
return await this.pageService.getPage(query) as any;
}
/**
* PUT /page/:pageId - 페이지 업데이트
*/
@Put(':pageId')
@ApiBearerAuth()
@ApiOperation({
summary: '페이지 업데이트',
description: '페이지의 제목, 내용, 부모 페이지, 정렬 순서 등을 업데이트합니다. (인증 필요)'
})
@ApiParam({
name: 'pageId',
description: '업데이트할 페이지 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '페이지가 성공적으로 업데이트됨',
type: PageResponseDto
})
@ApiBadRequestResponse({ description: '잘못된 요청 (순환 참조, 자기 자신을 부모로 설정 등)' })
@ApiNotFoundResponse({ description: '페이지 또는 부모 페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async updatePage(
@Param('pageId') pageId: string,
@Body() dto: Omit<UpdatePageDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<PageResponseDto> {
return await this.pageService.updatePage(pageId, {
...dto,
userId: user.oid
}) as any;
}
/**
* DELETE /page/:pageId - 페이지 삭제
*/
@Delete(':pageId')
@HttpCode(HttpStatus.OK)
@ApiBearerAuth()
@ApiOperation({
summary: '페이지 삭제',
description: '페이지를 소프트 삭제합니다 (isDeleted 플래그를 true로 설정). (인증 필요)'
})
@ApiParam({
name: 'pageId',
description: '삭제할 페이지 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '페이지가 성공적으로 삭제됨',
type: DeleteResponseDto
})
@ApiNotFoundResponse({ description: '페이지를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async deletePage(
@Param('pageId') pageId: string,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<DeleteResponseDto> {
return await this.pageService.deletePage(pageId, user.oid) as any;
}
/**
* POST /page/temporary-access-token - 임시 액세스 토큰 생성
*/
@Post('temporary-access-token')
@ApiBearerAuth()
@ApiOperation({
summary: '임시 액세스 토큰 생성',
description: '특정 페이지 또는 스페이스에 대한 접근 권한을 가진 임시 토큰을 생성합니다. 토큰은 여러 페이지/스페이스에 대한 권한을 배열로 가질 수 있습니다. (인증 필요)'
})
@ApiResponse({
status: 201,
description: '토큰이 성공적으로 생성됨',
type: CreateTokenResponseDto
})
@ApiBadRequestResponse({ description: 'pageIds 또는 spaceIds 중 최소 하나는 필수' })
@ApiNotFoundResponse({ description: '페이지 또는 스페이스를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async createTemporaryAccessToken(
@Body() dto: Omit<CreateTemporaryTokenDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<CreateTokenResponseDto> {
return await this.pageService.createTemporaryAccessToken({
...dto,
userId: user.oid
}) as any;
}
/**
* DELETE /page/temporary-access-token - 임시 액세스 토큰 삭제
*/
@Delete('temporary-access-token')
@HttpCode(HttpStatus.OK)
@ApiBearerAuth()
@ApiOperation({
summary: '임시 액세스 토큰 삭제',
description: '임시 액세스 토큰을 삭제합니다. 토큰 생성자만 삭제할 수 있습니다. (인증 필요)'
})
@ApiResponse({
status: 200,
description: '토큰이 성공적으로 삭제됨',
type: DeleteResponseDto
})
@ApiNotFoundResponse({ description: '토큰을 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패 또는 토큰 생성자만 삭제 가능' })
async deleteTemporaryAccessToken(
@Body() dto: Omit<DeleteTokenDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<DeleteResponseDto> {
return await this.pageService.deleteTemporaryAccessToken(dto.tokenValue, user.oid) as any;
}
}
+2
View File
@@ -1,8 +1,10 @@
import { Module } from "@nestjs/common";
import { PageController } from "./page.controller";
import { PageService } from "./page.service";
import { DatabaseModule } from "../global/database/database.module";
@Module({
imports: [DatabaseModule],
controllers: [PageController],
providers: [PageService],
})
+479 -2
View File
@@ -1,7 +1,484 @@
import { Injectable } from "@nestjs/common";
import { Injectable, NotFoundException, BadRequestException, UnauthorizedException } from "@nestjs/common";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { PageRepository, TokenRepository, SpaceRepository } from "../global/database/repositories";
import { randomBytes } from "crypto";
export class CreatePageDto {
@ApiProperty({
description: '페이지가 속할 스페이스 ID',
example: '550e8400-e29b-41d4-a716-446655440000',
format: 'uuid'
})
spaceId: string;
@ApiPropertyOptional({
description: '부모 페이지 ID (계층 구조)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid'
})
parentPageId?: string;
@ApiProperty({
description: '페이지 제목',
example: 'Getting Started',
maxLength: 255
})
title: string;
@ApiPropertyOptional({
description: '페이지 내용 (Markdown 등)',
example: '# Welcome\n\nThis is the content of the page.'
})
content?: string;
@ApiProperty({
description: '현재 사용자 ID (생성자)',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
@ApiPropertyOptional({
description: '페이지 정렬 순서',
example: 0,
default: 0
})
sortOrder?: number;
}
export class UpdatePageDto {
@ApiPropertyOptional({
description: '페이지 제목',
example: 'Updated Title',
maxLength: 255
})
title?: string;
@ApiPropertyOptional({
description: '페이지 내용',
example: '# Updated Content\n\nNew content here.'
})
content?: string;
@ApiPropertyOptional({
description: '부모 페이지 ID (null로 설정하면 루트 페이지가 됨)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid',
nullable: true
})
parentPageId?: string;
@ApiPropertyOptional({
description: '페이지 정렬 순서',
example: 1
})
sortOrder?: number;
@ApiProperty({
description: '현재 사용자 ID (수정자)',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
}
export class GetPageQuery {
@ApiPropertyOptional({
description: '조회할 페이지 ID',
example: '550e8400-e29b-41d4-a716-446655440000',
format: 'uuid'
})
pageId?: string;
@ApiPropertyOptional({
description: '조회할 스페이스 ID (해당 스페이스의 모든 페이지 반환)',
example: '550e8400-e29b-41d4-a716-446655440001',
format: 'uuid'
})
spaceId?: string;
}
export class CreateTemporaryTokenDto {
@ApiPropertyOptional({
description: '접근 권한을 부여할 페이지 ID 배열',
example: ['550e8400-e29b-41d4-a716-446655440000', '550e8400-e29b-41d4-a716-446655440001'],
type: [String],
isArray: true
})
pageIds?: string[];
@ApiPropertyOptional({
description: '접근 권한을 부여할 스페이스 ID 배열',
example: ['550e8400-e29b-41d4-a716-446655440002'],
type: [String],
isArray: true
})
spaceIds?: string[];
@ApiPropertyOptional({
description: '토큰 만료 시간 (시간 단위). 생략하면 만료되지 않음',
example: 24,
minimum: 1
})
expiresInHours?: number;
@ApiPropertyOptional({
description: '토큰 설명',
example: '24시간 공유 링크',
maxLength: 255
})
description?: string;
@ApiProperty({
description: '현재 사용자 ID (토큰 생성자)',
example: '550e8400-e29b-41d4-a716-446655440003',
format: 'uuid'
})
userId: string;
}
export class DeletePageDto {
@ApiProperty({
description: '현재 사용자 ID',
example: '550e8400-e29b-41d4-a716-446655440002',
format: 'uuid'
})
userId: string;
}
export class DeleteTokenDto {
@ApiProperty({
description: '삭제할 토큰 값',
example: 'abc123def456ghi789jkl012mno345pqr678stu901vwx234yz'
})
tokenValue: string;
@ApiProperty({
description: '현재 사용자 ID (토큰 생성자만 삭제 가능)',
example: '550e8400-e29b-41d4-a716-446655440003',
format: 'uuid'
})
userId: string;
}
export class PageResponseDto {
@ApiProperty({ description: '페이지 ID', format: 'uuid' })
pageId: string;
@ApiProperty({ description: '스페이스 ID', format: 'uuid' })
spaceId: string;
@ApiProperty({ description: '부모 페이지 ID', format: 'uuid', nullable: true })
parentPageId: string | null;
@ApiProperty({ description: '정렬 순서' })
sortOrder: number;
@ApiProperty({ description: '페이지 제목' })
title: string;
@ApiProperty({ description: '페이지 내용', nullable: true })
content: string | null;
@ApiProperty({ description: '생성자 사용자 ID', format: 'uuid' })
createdByUserId: string;
@ApiProperty({ description: '수정자 사용자 ID', format: 'uuid' })
updatedByUserId: string;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
@ApiProperty({ description: '수정 시간', format: 'date-time' })
updatedAt: string;
@ApiProperty({ description: '삭제 여부' })
isDeleted: boolean;
}
export class TokenInfoDto {
@ApiProperty({ description: '토큰 ID', format: 'uuid' })
tokenId: string;
@ApiProperty({ description: '토큰 값 (실제 사용할 토큰 문자열)' })
tokenValue: string;
@ApiProperty({ description: '토큰 설명', nullable: true })
description: string | null;
@ApiProperty({ description: '만료 시간', format: 'date-time', nullable: true })
expiresAt: string | null;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
}
export class TokenPermissionsDto {
@ApiProperty({ description: '권한이 부여된 페이지 ID 목록', type: [String] })
pageIds: string[];
@ApiProperty({ description: '권한이 부여된 스페이스 ID 목록', type: [String] })
spaceIds: string[];
}
export class CreateTokenResponseDto {
@ApiProperty({ description: '생성된 토큰 정보', type: TokenInfoDto })
token: TokenInfoDto;
@ApiProperty({ description: '토큰 권한 정보', type: TokenPermissionsDto })
permissions: TokenPermissionsDto;
}
export class DeleteResponseDto {
@ApiProperty({ description: '응답 메시지' })
message: string;
@ApiProperty({ description: '삭제된 리소스 ID', format: 'uuid' })
pageId?: string;
@ApiProperty({ description: '삭제된 토큰 ID', format: 'uuid' })
tokenId?: string;
}
@Injectable()
export class PageService {
constructor(
private readonly pageRepository: PageRepository,
private readonly tokenRepository: TokenRepository,
private readonly spaceRepository: SpaceRepository,
) {}
/**
* 페이지 생성
*/
async createPage(dto: CreatePageDto) {
// 스페이스 존재 확인
const space = await this.spaceRepository.findById(dto.spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${dto.spaceId}' not found`);
}
// 부모 페이지 존재 확인 (있는 경우)
if (dto.parentPageId) {
const parentPage = await this.pageRepository.findById(dto.parentPageId);
if (!parentPage) {
throw new NotFoundException(`Parent page with id '${dto.parentPageId}' not found`);
}
// 부모 페이지가 같은 스페이스에 있는지 확인
if (parentPage.spaceId !== dto.spaceId) {
throw new BadRequestException('Parent page must be in the same space');
}
}
const page = await this.pageRepository.create({
spaceId: dto.spaceId,
parentPageId: dto.parentPageId,
title: dto.title,
content: dto.content,
createdByUserId: dto.userId,
updatedByUserId: dto.userId,
sortOrder: dto.sortOrder,
});
return page;
}
/**
* 페이지 조회
*/
async getPage(query: GetPageQuery) {
if (query.pageId) {
// 특정 페이지 조회
const page = await this.pageRepository.findById(query.pageId);
if (!page) {
throw new NotFoundException(`Page with id '${query.pageId}' not found`);
}
return page;
} else if (query.spaceId) {
// 스페이스의 모든 페이지 조회
const space = await this.spaceRepository.findById(query.spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${query.spaceId}' not found`);
}
const pages = await this.pageRepository.findBySpaceId(query.spaceId);
return pages;
} else {
throw new BadRequestException('Either pageId or spaceId must be provided');
}
}
/**
* 페이지 업데이트
*/
async updatePage(pageId: string, dto: UpdatePageDto) {
const existingPage = await this.pageRepository.findById(pageId);
if (!existingPage) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
// 부모 페이지 변경 시 검증
if (dto.parentPageId !== undefined) {
if (dto.parentPageId === pageId) {
throw new BadRequestException('A page cannot be its own parent');
}
if (dto.parentPageId) {
const parentPage = await this.pageRepository.findById(dto.parentPageId);
if (!parentPage) {
throw new NotFoundException(`Parent page with id '${dto.parentPageId}' not found`);
}
if (parentPage.spaceId !== existingPage.spaceId) {
throw new BadRequestException('Parent page must be in the same space');
}
// 순환 참조 확인
const isDescendant = await this.isPageDescendant(pageId, dto.parentPageId);
if (isDescendant) {
throw new BadRequestException('Cannot move a page to one of its descendants');
}
}
}
const updatedPage = await this.pageRepository.update(pageId, {
title: dto.title,
content: dto.content,
parentPageId: dto.parentPageId,
sortOrder: dto.sortOrder,
updatedByUserId: dto.userId,
});
return updatedPage;
}
/**
* 페이지 삭제 (소프트 삭제)
*/
async deletePage(pageId: string, userId: string) {
const page = await this.pageRepository.findById(pageId);
if (!page) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
await this.pageRepository.softDelete(pageId, userId);
return { message: 'Page deleted successfully', pageId };
}
/**
* 임시 액세스 토큰 생성
*/
async createTemporaryAccessToken(dto: CreateTemporaryTokenDto) {
if ((!dto.pageIds || dto.pageIds.length === 0) && (!dto.spaceIds || dto.spaceIds.length === 0)) {
throw new BadRequestException('At least one pageId or spaceId must be provided');
}
// 페이지 존재 확인
if (dto.pageIds && dto.pageIds.length > 0) {
for (const pageId of dto.pageIds) {
const page = await this.pageRepository.findById(pageId);
if (!page) {
throw new NotFoundException(`Page with id '${pageId}' not found`);
}
}
}
// 스페이스 존재 확인
if (dto.spaceIds && dto.spaceIds.length > 0) {
for (const spaceId of dto.spaceIds) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
}
}
// 토큰 값 생성 (안전한 랜덤 문자열)
const tokenValue = randomBytes(32).toString('base64url');
// 만료 시간 계산
const expiresAt = dto.expiresInHours
? new Date(Date.now() + dto.expiresInHours * 60 * 60 * 1000).toISOString()
: undefined;
// 토큰 생성
const token = await this.tokenRepository.createToken({
tokenValue,
description: dto.description || 'Temporary access token',
expiresAt,
createdByUserId: dto.userId,
});
// 권한 생성
const permissions: any[] = [];
// 페이지 권한 추가
if (dto.pageIds && dto.pageIds.length > 0) {
for (const pageId of dto.pageIds) {
const permission = await this.tokenRepository.createPermission({
tokenId: token.tokenId,
pageId,
});
permissions.push(permission);
}
}
// 스페이스 권한 추가
if (dto.spaceIds && dto.spaceIds.length > 0) {
for (const spaceId of dto.spaceIds) {
const permission = await this.tokenRepository.createPermission({
tokenId: token.tokenId,
spaceId,
});
permissions.push(permission);
}
}
return {
token: {
tokenId: token.tokenId,
tokenValue: token.tokenValue,
description: token.description,
expiresAt: token.expiresAt,
createdAt: token.createdAt,
},
permissions: {
pageIds: dto.pageIds || [],
spaceIds: dto.spaceIds || [],
},
};
}
/**
* 임시 액세스 토큰 삭제
*/
async deleteTemporaryAccessToken(tokenValue: string, userId: string) {
const token = await this.tokenRepository.findTokenByValue(tokenValue);
if (!token) {
throw new NotFoundException('Token not found');
}
// 토큰 생성자만 삭제 가능
if (token.createdByUserId !== userId) {
throw new UnauthorizedException('You can only delete tokens you created');
}
await this.tokenRepository.deleteToken(token.tokenId);
return { message: 'Token deleted successfully', tokenId: token.tokenId };
}
/**
* 페이지가 다른 페이지의 자손인지 확인 (재귀)
*/
private async isPageDescendant(ancestorId: string, pageId: string): Promise<boolean> {
const page = await this.pageRepository.findById(pageId);
if (!page || !page.parentPageId) {
return false;
}
if (page.parentPageId === ancestorId) {
return true;
}
return await this.isPageDescendant(ancestorId, page.parentPageId);
}
}
+392
View File
@@ -0,0 +1,392 @@
# Space API Documentation
## Endpoints
### 1. POST /space
스페이스를 생성합니다.
**Request Body:**
```json
{
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "Engineering team documentation and knowledge base (optional)",
"userId": "uuid"
}
```
**Validation:**
- `spaceKey`: 소문자, 숫자, 하이픈만 허용 (^[a-z0-9-]+$)
- `spaceKey`: 고유해야 함 (중복 시 409 Conflict)
- `spaceKey`: 최대 50자
- `name`: 최대 255자
**Response:**
```json
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "Engineering team documentation and knowledge base",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
}
```
---
### 2. GET /space
모든 스페이스를 조회합니다.
**Query Parameters:**
- `withCreator` (optional, boolean): 생성자 정보 포함 여부
**Examples:**
기본 조회:
```
GET /space
```
생성자 정보 포함:
```
GET /space?withCreator=true
```
**Response (기본):**
```json
[
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
},
...
]
```
**Response (withCreator=true):**
```json
[
{
"space": {
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
},
"creator": {
"userId": "uuid",
"email": "user@example.com",
"displayName": "John Doe"
}
},
...
]
```
---
### 3. GET /space/:spaceId
스페이스 ID로 특정 스페이스를 조회합니다.
**URL Parameters:**
- `spaceId`: 조회할 스페이스 ID (uuid)
**Query Parameters:**
- `withCreator` (optional, boolean): 생성자 정보 포함 여부
**Response:**
```json
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
}
```
---
### 4. GET /space/key/:spaceKey
스페이스 키로 특정 스페이스를 조회합니다. URL 친화적인 조회 방법입니다.
**URL Parameters:**
- `spaceKey`: 조회할 스페이스 키 (예: "engineering")
**Example:**
```
GET /space/key/engineering
```
**Response:**
```json
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
}
```
---
### 5. GET /space/:spaceId/statistics
스페이스의 통계 정보를 조회합니다.
**URL Parameters:**
- `spaceId`: 통계를 조회할 스페이스 ID (uuid)
**Response:**
```json
{
"space": {
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
},
"statistics": {
"totalPages": 42,
"rootPages": 5
}
}
```
---
### 6. GET /space/user/:userId
특정 사용자가 생성한 모든 스페이스를 조회합니다.
**URL Parameters:**
- `userId`: 사용자 ID (uuid)
**Response:**
```json
[
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "...",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
},
...
]
```
---
### 7. PUT /space/:spaceId
스페이스 정보를 업데이트합니다.
**URL Parameters:**
- `spaceId`: 업데이트할 스페이스 ID (uuid)
**Request Body:**
```json
{
"name": "Updated Team Name (optional)",
"description": "Updated description (optional)"
}
```
**Note:** 스페이스 키(`spaceKey`)는 변경할 수 없습니다.
**Response:**
```json
{
"spaceId": "uuid",
"spaceKey": "engineering",
"name": "Updated Team Name",
"description": "Updated description",
"createdByUserId": "uuid",
"createdAt": "2024-01-01T00:00:00.000Z"
}
```
---
### 8. DELETE /space/:spaceId
스페이스를 삭제합니다.
**URL Parameters:**
- `spaceId`: 삭제할 스페이스 ID (uuid)
**Warning:** CASCADE 설정으로 해당 스페이스의 모든 페이지도 함께 삭제됩니다.
**Response:**
```json
{
"message": "Space deleted successfully",
"spaceId": "uuid"
}
```
---
## Error Responses
### 400 Bad Request
```json
{
"statusCode": 400,
"message": "Space key must contain only lowercase letters, numbers, and hyphens",
"error": "Bad Request"
}
```
### 404 Not Found
```json
{
"statusCode": 404,
"message": "Space with id 'uuid' not found",
"error": "Not Found"
}
```
### 409 Conflict
```json
{
"statusCode": 409,
"message": "Space with key 'engineering' already exists",
"error": "Conflict"
}
```
---
## Space Key 규칙
스페이스 키는 URL에 사용되는 고유 식별자입니다:
- ✅ 소문자 영문자 (a-z)
- ✅ 숫자 (0-9)
- ✅ 하이픈 (-)
- ❌ 대문자, 공백, 특수문자 불가
- 최대 50자
- 고유해야 함 (중복 불가)
**Valid Examples:**
- `engineering`
- `product-team`
- `team-2024`
- `hr-docs`
**Invalid Examples:**
- `Engineering` (대문자)
- `product team` (공백)
- `team_2024` (언더스코어)
- `hr@docs` (특수문자)
---
## Use Cases
### 1. 스페이스 생성 및 페이지 추가
```bash
# 1. 스페이스 생성
curl -X POST http://localhost:3415/v1/space \
-H "Content-Type: application/json" \
-d '{
"spaceKey": "engineering",
"name": "Engineering Team",
"description": "Engineering documentation",
"userId": "user-uuid"
}'
# Response: { "spaceId": "space-uuid", ... }
# 2. 스페이스에 페이지 추가
curl -X POST http://localhost:3415/v1/page \
-H "Content-Type: application/json" \
-d '{
"spaceId": "space-uuid",
"title": "Getting Started",
"content": "# Welcome",
"userId": "user-uuid"
}'
```
### 2. URL 친화적인 접근
```bash
# 스페이스 키로 조회 (사용자 친화적)
curl http://localhost:3415/v1/space/key/engineering
# 스페이스의 모든 페이지 조회
curl http://localhost:3415/v1/page?spaceId=space-uuid
```
### 3. 대시보드용 통계 조회
```bash
# 모든 스페이스와 생성자 정보
curl http://localhost:3415/v1/space?withCreator=true
# 특정 스페이스 통계
curl http://localhost:3415/v1/space/space-uuid/statistics
```
---
## Integration with Page API
스페이스와 페이지는 밀접하게 연관되어 있습니다:
### 계층 구조
```
Space (engineering)
├── Page 1 (Getting Started)
│ ├── Page 1.1 (Installation)
│ └── Page 1.2 (Configuration)
├── Page 2 (Architecture)
└── Page 3 (API Reference)
```
### 데이터베이스 관계
- 페이지는 반드시 하나의 스페이스에 속함
- 스페이스 삭제 시 모든 페이지도 CASCADE로 삭제됨
- 페이지는 `spaceId` 외래 키로 스페이스 참조
### 권한 모델
토큰 권한은 스페이스 레벨 또는 페이지 레벨로 부여 가능:
- **스페이스 권한**: 해당 스페이스의 모든 페이지 접근 가능
- **페이지 권한**: 특정 페이지만 접근 가능
---
## Best Practices
### 1. 스페이스 키 네이밍
- 팀/부서 이름 사용: `engineering`, `marketing`, `hr`
- 프로젝트 이름 사용: `project-alpha`, `mobile-app`
- 목적 기반: `public-docs`, `internal-wiki`
### 2. 스페이스 구조화
- 큰 조직: 부서별 스페이스 생성
- 작은 팀: 프로젝트별 스페이스 생성
- 문서 타입별: `tutorials`, `api-docs`, `guides`
### 3. 삭제 주의
- 스페이스 삭제는 되돌릴 수 없음
- 모든 페이지가 함께 삭제됨
- 중요한 데이터는 백업 후 삭제
### 4. 통계 활용
- 대시보드에 스페이스 통계 표시
- 활동이 없는 스페이스 식별
- 페이지 수로 스페이스 크기 파악
+270
View File
@@ -0,0 +1,270 @@
import { Controller, Post, Get, Put, Delete, Body, Param, Query, HttpCode, HttpStatus, UseGuards } from "@nestjs/common";
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiParam,
ApiQuery,
ApiBadRequestResponse,
ApiNotFoundResponse,
ApiConflictResponse,
ApiUnauthorizedResponse,
ApiBearerAuth
} from "@nestjs/swagger";
import {
SpaceService,
CreateSpaceDto,
UpdateSpaceDto,
SpaceResponseDto,
SpaceWithCreatorDto,
SpaceStatisticsDto,
DeleteSpaceResponseDto
} from "./space.service";
import { AllowPublicAccess } from "../global/auth/allow-public-access.decorator";
import { ExtractUserPayloadFromToken } from "../global/auth/extract-user-payload-from-token.decorator";
import { type EntraIDPayloadClaims } from "../global/auth/jwt.service";
import { JwtAuthGuard } from "../global/auth/jwt.guard";
@ApiTags('Space')
@UseGuards(JwtAuthGuard)
@Controller('space')
export class SpaceController {
constructor(private readonly spaceService: SpaceService) {}
/**
* POST /space - 스페이스 생성
*/
@Post()
@ApiBearerAuth()
@ApiOperation({
summary: '스페이스 생성',
description: '새로운 스페이스를 생성합니다. 스페이스 키는 고유해야 하며 URL에 사용됩니다. (인증 필요)'
})
@ApiResponse({
status: 201,
description: '스페이스가 성공적으로 생성됨',
type: SpaceResponseDto
})
@ApiBadRequestResponse({ description: '잘못된 요청 (스페이스 키 형식 오류 등)' })
@ApiNotFoundResponse({ description: '사용자를 찾을 수 없음' })
@ApiConflictResponse({ description: '스페이스 키가 이미 존재함' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async createSpace(
@Body() dto: Omit<CreateSpaceDto, 'userId'>,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<SpaceResponseDto> {
return await this.spaceService.createSpace({
...dto,
userId: user.oid
}) as any;
}
/**
* GET /space - 모든 스페이스 조회
*/
@Get()
@AllowPublicAccess()
@ApiOperation({
summary: '모든 스페이스 조회',
description: '시스템의 모든 스페이스를 조회합니다. withCreator 파라미터로 생성자 정보 포함 여부를 선택할 수 있습니다. (공개 접근 가능)'
})
@ApiQuery({
name: 'withCreator',
required: false,
description: '생성자 정보 포함 여부',
type: Boolean
})
@ApiResponse({
status: 200,
description: '스페이스 목록 조회 성공',
type: SpaceResponseDto,
isArray: true
})
async getAllSpaces(
@Query('withCreator') withCreator?: boolean
): Promise<SpaceResponseDto[] | SpaceWithCreatorDto[]> {
if (withCreator) {
return await this.spaceService.getAllSpacesWithCreator() as any;
}
return await this.spaceService.getAllSpaces() as any;
}
/**
* GET /space/:spaceId - 스페이스 ID로 조회
*/
@Get(':spaceId')
@AllowPublicAccess()
@ApiOperation({
summary: '스페이스 ID로 조회',
description: '특정 스페이스를 ID로 조회합니다. withCreator 파라미터로 생성자 정보 포함 여부를 선택할 수 있습니다. (공개 접근 가능)'
})
@ApiParam({
name: 'spaceId',
description: '조회할 스페이스 ID',
type: String,
format: 'uuid'
})
@ApiQuery({
name: 'withCreator',
required: false,
description: '생성자 정보 포함 여부',
type: Boolean
})
@ApiResponse({
status: 200,
description: '스페이스 조회 성공',
type: SpaceResponseDto
})
@ApiNotFoundResponse({ description: '스페이스를 찾을 수 없음' })
async getSpaceById(
@Param('spaceId') spaceId: string,
@Query('withCreator') withCreator?: boolean
): Promise<SpaceResponseDto | SpaceWithCreatorDto> {
if (withCreator) {
return await this.spaceService.getSpaceWithCreator(spaceId) as any;
}
return await this.spaceService.getSpaceById(spaceId) as any;
}
/**
* GET /space/key/:spaceKey - 스페이스 키로 조회
*/
@Get('key/:spaceKey')
@AllowPublicAccess()
@ApiOperation({
summary: '스페이스 키로 조회',
description: '특정 스페이스를 키로 조회합니다. URL 친화적인 식별자로 사용됩니다. (공개 접근 가능)'
})
@ApiParam({
name: 'spaceKey',
description: '조회할 스페이스 키',
type: String,
example: 'engineering'
})
@ApiResponse({
status: 200,
description: '스페이스 조회 성공',
type: SpaceResponseDto
})
@ApiNotFoundResponse({ description: '스페이스를 찾을 수 없음' })
async getSpaceByKey(
@Param('spaceKey') spaceKey: string
): Promise<SpaceResponseDto> {
return await this.spaceService.getSpaceByKey(spaceKey) as any;
}
/**
* GET /space/:spaceId/statistics - 스페이스 통계 조회
*/
@Get(':spaceId/statistics')
@AllowPublicAccess()
@ApiOperation({
summary: '스페이스 통계 조회',
description: '스페이스의 통계 정보(전체 페이지 수, 루트 페이지 수 등)를 조회합니다. (공개 접근 가능)'
})
@ApiParam({
name: 'spaceId',
description: '통계를 조회할 스페이스 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '스페이스 통계 조회 성공',
type: SpaceStatisticsDto
})
@ApiNotFoundResponse({ description: '스페이스를 찾을 수 없음' })
async getSpaceStatistics(
@Param('spaceId') spaceId: string
): Promise<SpaceStatisticsDto> {
return await this.spaceService.getSpaceStatistics(spaceId) as any;
}
/**
* GET /space/user/:userId - 사용자가 생성한 스페이스 조회
*/
@Get('user/:userId')
@AllowPublicAccess()
@ApiOperation({
summary: '사용자가 생성한 스페이스 조회',
description: '특정 사용자가 생성한 모든 스페이스를 조회합니다. (공개 접근 가능)'
})
@ApiParam({
name: 'userId',
description: '사용자 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '사용자의 스페이스 목록 조회 성공',
type: SpaceResponseDto,
isArray: true
})
@ApiNotFoundResponse({ description: '사용자를 찾을 수 없음' })
async getSpacesByCreator(
@Param('userId') userId: string
): Promise<SpaceResponseDto[]> {
return await this.spaceService.getSpacesByCreator(userId) as any;
}
/**
* PUT /space/:spaceId - 스페이스 업데이트
*/
@Put(':spaceId')
@ApiBearerAuth()
@ApiOperation({
summary: '스페이스 업데이트',
description: '스페이스의 이름과 설명을 업데이트합니다. 스페이스 키는 변경할 수 없습니다. (인증 필요)'
})
@ApiParam({
name: 'spaceId',
description: '업데이트할 스페이스 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '스페이스가 성공적으로 업데이트됨',
type: SpaceResponseDto
})
@ApiNotFoundResponse({ description: '스페이스를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async updateSpace(
@Param('spaceId') spaceId: string,
@Body() dto: UpdateSpaceDto,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<SpaceResponseDto> {
return await this.spaceService.updateSpace(spaceId, dto) as any;
}
/**
* DELETE /space/:spaceId - 스페이스 삭제
*/
@Delete(':spaceId')
@HttpCode(HttpStatus.OK)
@ApiBearerAuth()
@ApiOperation({
summary: '스페이스 삭제',
description: '스페이스를 삭제합니다. CASCADE 설정으로 해당 스페이스의 모든 페이지도 함께 삭제됩니다. (인증 필요)'
})
@ApiParam({
name: 'spaceId',
description: '삭제할 스페이스 ID',
type: String,
format: 'uuid'
})
@ApiResponse({
status: 200,
description: '스페이스가 성공적으로 삭제됨',
type: DeleteSpaceResponseDto
})
@ApiNotFoundResponse({ description: '스페이스를 찾을 수 없음' })
@ApiUnauthorizedResponse({ description: '인증 실패' })
async deleteSpace(
@Param('spaceId') spaceId: string,
@ExtractUserPayloadFromToken() user: EntraIDPayloadClaims
): Promise<DeleteSpaceResponseDto> {
return await this.spaceService.deleteSpace(spaceId) as any;
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from "@nestjs/common";
import { SpaceController } from "./space.controller";
import { SpaceService } from "./space.service";
import { DatabaseModule } from "../global/database/database.module";
@Module({
imports: [DatabaseModule],
controllers: [SpaceController],
providers: [SpaceService],
exports: [SpaceService],
})
export class SpaceModule {}
+249
View File
@@ -0,0 +1,249 @@
import { Injectable, NotFoundException, BadRequestException, ConflictException } from "@nestjs/common";
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { SpaceRepository, PageRepository, UserRepository } from "../global/database/repositories";
export class CreateSpaceDto {
@ApiProperty({
description: '스페이스 키 (고유 식별자, URL에 사용)',
example: 'engineering',
maxLength: 50,
pattern: '^[a-z0-9-]+$'
})
spaceKey: string;
@ApiProperty({
description: '스페이스 이름',
example: 'Engineering Team',
maxLength: 255
})
name: string;
@ApiPropertyOptional({
description: '스페이스 설명',
example: 'Engineering team documentation and knowledge base'
})
description?: string;
@ApiProperty({
description: '현재 사용자 ID (생성자)',
example: '550e8400-e29b-41d4-a716-446655440000',
format: 'uuid'
})
userId: string;
}
export class UpdateSpaceDto {
@ApiPropertyOptional({
description: '스페이스 이름',
example: 'Updated Team Name',
maxLength: 255
})
name?: string;
@ApiPropertyOptional({
description: '스페이스 설명',
example: 'Updated description'
})
description?: string;
}
export class SpaceResponseDto {
@ApiProperty({ description: '스페이스 ID', format: 'uuid' })
spaceId: string;
@ApiProperty({ description: '스페이스 키 (고유 식별자)' })
spaceKey: string;
@ApiProperty({ description: '스페이스 이름' })
name: string;
@ApiProperty({ description: '스페이스 설명', nullable: true })
description: string | null;
@ApiProperty({ description: '생성자 사용자 ID', format: 'uuid' })
createdByUserId: string;
@ApiProperty({ description: '생성 시간', format: 'date-time' })
createdAt: string;
}
export class SpaceWithCreatorDto {
@ApiProperty({ description: '스페이스 정보', type: SpaceResponseDto })
space: SpaceResponseDto;
@ApiProperty({ description: '생성자 정보' })
creator: {
userId: string;
email: string;
displayName: string;
};
}
export class SpaceStatisticsDto {
@ApiProperty({ description: '스페이스 정보', type: SpaceResponseDto })
space: SpaceResponseDto;
@ApiProperty({ description: '통계 정보' })
statistics: {
totalPages: number;
rootPages: number;
};
}
export class DeleteSpaceResponseDto {
@ApiProperty({ description: '응답 메시지' })
message: string;
@ApiProperty({ description: '삭제된 스페이스 ID', format: 'uuid' })
spaceId: string;
}
@Injectable()
export class SpaceService {
constructor(
private readonly spaceRepository: SpaceRepository,
private readonly pageRepository: PageRepository,
private readonly userRepository: UserRepository,
) {}
/**
* 스페이스 생성
*/
async createSpace(dto: CreateSpaceDto) {
// 스페이스 키 중복 확인
const exists = await this.spaceRepository.existsByKey(dto.spaceKey);
if (exists) {
throw new ConflictException(`Space with key '${dto.spaceKey}' already exists`);
}
// 사용자 존재 확인
const user = await this.userRepository.findById(dto.userId);
if (!user) {
throw new NotFoundException(`User with id '${dto.userId}' not found`);
}
// 스페이스 키 형식 검증 (소문자, 숫자, 하이픈만 허용)
const spaceKeyRegex = /^[a-z0-9-]+$/;
if (!spaceKeyRegex.test(dto.spaceKey)) {
throw new BadRequestException('Space key must contain only lowercase letters, numbers, and hyphens');
}
const space = await this.spaceRepository.create({
spaceKey: dto.spaceKey,
name: dto.name,
description: dto.description,
createdByUserId: dto.userId,
});
return space;
}
/**
* 스페이스 ID로 조회
*/
async getSpaceById(spaceId: string) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
return space;
}
/**
* 스페이스 키로 조회
*/
async getSpaceByKey(spaceKey: string) {
const space = await this.spaceRepository.findByKey(spaceKey);
if (!space) {
throw new NotFoundException(`Space with key '${spaceKey}' not found`);
}
return space;
}
/**
* 모든 스페이스 조회
*/
async getAllSpaces() {
return await this.spaceRepository.findAll();
}
/**
* 생성자 정보와 함께 스페이스 조회
*/
async getSpaceWithCreator(spaceId: string) {
const result = await this.spaceRepository.findByIdWithCreator(spaceId);
if (!result) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
return result;
}
/**
* 모든 스페이스를 생성자 정보와 함께 조회
*/
async getAllSpacesWithCreator() {
return await this.spaceRepository.findAllWithCreator();
}
/**
* 스페이스 통계 조회
*/
async getSpaceStatistics(spaceId: string) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
const allPages = await this.pageRepository.findBySpaceId(spaceId);
const rootPages = await this.pageRepository.findRootPagesBySpaceId(spaceId);
return {
space,
statistics: {
totalPages: allPages.length,
rootPages: rootPages.length,
},
};
}
/**
* 사용자가 생성한 스페이스 조회
*/
async getSpacesByCreator(userId: string) {
const user = await this.userRepository.findById(userId);
if (!user) {
throw new NotFoundException(`User with id '${userId}' not found`);
}
return await this.spaceRepository.findByCreator(userId);
}
/**
* 스페이스 업데이트
*/
async updateSpace(spaceId: string, dto: UpdateSpaceDto) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
const updatedSpace = await this.spaceRepository.update(spaceId, dto);
return updatedSpace;
}
/**
* 스페이스 삭제 (cascade로 페이지도 함께 삭제됨)
*/
async deleteSpace(spaceId: string) {
const space = await this.spaceRepository.findById(spaceId);
if (!space) {
throw new NotFoundException(`Space with id '${spaceId}' not found`);
}
await this.spaceRepository.delete(spaceId);
return {
message: 'Space deleted successfully',
spaceId
};
}
}