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:
1 parent
ef440a2dbd
commit
bb992167d2
10 files changed
+2315
-5
No files matched your search
@@ -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. 통계 활용
|
||||
- 대시보드에 스페이스 통계 표시
|
||||
- 활동이 없는 스페이스 식별
|
||||
- 페이지 수로 스페이스 크기 파악
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user