|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { SpacesService } from '../spaces/spaces.service'; |
| 3 | +import { DocumentsService } from '../documents/documents.service'; |
| 4 | +import { PrismaService } from '../prisma/prisma.service'; |
| 5 | +import { tiptapJsonToYDocBinary } from '../common/ydoc-utils'; |
| 6 | +import { |
| 7 | + WELCOME_DOCUMENT_TITLE, |
| 8 | + WELCOME_DOCUMENT_CONTENT, |
| 9 | + WELCOME_CONTENT_JSON, |
| 10 | + DEFAULT_SPACE_NAME, |
| 11 | + DEFAULT_SPACE_DESCRIPTION, |
| 12 | +} from './welcome-document.seed'; |
| 13 | + |
| 14 | +@Injectable() |
| 15 | +export class OnboardingService { |
| 16 | + private readonly logger = new Logger(OnboardingService.name); |
| 17 | + |
| 18 | + constructor( |
| 19 | + private readonly spacesService: SpacesService, |
| 20 | + private readonly documentsService: DocumentsService, |
| 21 | + private readonly prisma: PrismaService, |
| 22 | + ) {} |
| 23 | + |
| 24 | + /** |
| 25 | + * 为新用户创建默认工作空间和欢迎文档。 |
| 26 | + * Fire-and-forget:失败仅打日志,不阻塞注册流程。 |
| 27 | + */ |
| 28 | + async setupNewUser(userId: string): Promise<void> { |
| 29 | + try { |
| 30 | + // 1. 创建默认空间 |
| 31 | + const space = await this.spacesService.create(userId, { |
| 32 | + name: DEFAULT_SPACE_NAME, |
| 33 | + description: DEFAULT_SPACE_DESCRIPTION, |
| 34 | + }); |
| 35 | + |
| 36 | + this.logger.log( |
| 37 | + `Created default space "${space.name}" (${space.id}) for user ${userId}`, |
| 38 | + ); |
| 39 | + |
| 40 | + // 2. 在空间中创建欢迎文档 |
| 41 | + const document = await this.documentsService.create( |
| 42 | + space.id, |
| 43 | + userId, |
| 44 | + { |
| 45 | + title: WELCOME_DOCUMENT_TITLE, |
| 46 | + content: WELCOME_DOCUMENT_CONTENT, |
| 47 | + }, |
| 48 | + ); |
| 49 | + |
| 50 | + // 3. 生成 Yjs 二进制数据,使文档通过协作路径加载(与用户手动创建的文档一致) |
| 51 | + const ydocData = tiptapJsonToYDocBinary(WELCOME_CONTENT_JSON); |
| 52 | + await this.prisma.document.update({ |
| 53 | + where: { id: document.id }, |
| 54 | + data: { ydocData }, |
| 55 | + }); |
| 56 | + |
| 57 | + this.logger.log( |
| 58 | + `Created welcome document "${document.title}" (${document.id}) in space ${space.id}`, |
| 59 | + ); |
| 60 | + } catch (error: unknown) { |
| 61 | + const message = |
| 62 | + error instanceof Error ? error.message : 'Unknown error'; |
| 63 | + this.logger.error( |
| 64 | + `Failed to setup onboarding for user ${userId}: ${message}`, |
| 65 | + error instanceof Error ? error.stack : undefined, |
| 66 | + ); |
| 67 | + // 不抛出异常 — 注册流程不受影响 |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments