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,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"
|
||||
}'
|
||||
```
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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],
|
||||
})
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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