refactor: extract core service domain layer to @shumai/core

This commit is contained in:
yiling
2026-06-01 23:16:22 +08:00
parent 2362a7f373
commit cb80822637
163 changed files with 328 additions and 67608 deletions
+271
View File
@@ -0,0 +1,271 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { shareService } from './share'
import { assetService } from '@shumai/core/src/asset/asset'
import { projectService } from '@shumai/core/src/project/project'
import { AssetType } from '@shumai/db'
describe('ShareService', () => {
setupTestDbHooks()
let teamId: string
let projectId: string
let userId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
userId = user.id
const team = await prisma.team.create({ data: { name: 'Test Team' } })
teamId = team.id
await prisma.teamMember.create({
data: { teamId, userId, role: 'owner' },
})
const project = await projectService.createProject(
{ id: userId },
{
name: 'Test Project',
teamId,
},
)
projectId = project.id
})
it('creates a share link and its root folder', async () => {
const shareLink = await shareService.createShareLink(projectId, {
name: 'Public Share',
})
expect(shareLink.name).toBe('Public Share')
expect(shareLink.rootFolderId).toBeDefined()
const asset = await prisma.asset.findUnique({
where: { id: shareLink.rootFolderId },
})
expect(asset?.type).toBe(AssetType.share)
expect(asset?.projectId).toBe(projectId)
})
it('adds multiple assets to share and handles duplicates', async () => {
// Create real assets
const file1 = await prisma.asset.create({
data: {
name: 'file1.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const file2 = await prisma.asset.create({
data: {
name: 'file2.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const shareLink = await shareService.createShareLink(projectId, {
name: 'Batch Share',
})
// Add first asset
const count1 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id],
})
expect(count1).toBe(1)
// Add both assets (one is duplicate)
const count2 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id, file2.id],
})
expect(count2).toBe(1) // Only file2 added
// Add both again (all duplicates)
const count3 = await shareService.addAssetToShare(shareLink.id, {
assetIds: [file1.id, file2.id],
})
expect(count3).toBe(0)
// List children of the share root folder
const children = await assetService.listChildren({
assetId: shareLink.rootFolderId,
assetType: 'file',
})
expect(children.data).toHaveLength(2)
})
it('verifies public access correctly', async () => {
const file = await prisma.asset.create({
data: {
name: 'data.png',
type: AssetType.file,
status: 'processed',
projectId,
},
})
const shareLink = await shareService.createShareLink(projectId, {
name: 'Protected Share',
password: 'secret-password',
})
await shareService.addAssetToShare(shareLink.id, {
assetIds: [file.id],
})
const symlink = await prisma.asset.findFirst({
where: { targetId: file.id, parentId: shareLink.rootFolderId },
})
expect(symlink).toBeDefined()
// Test password check
await expect(shareService.verifyPublicAccess(symlink!.id, 'wrong')).rejects.toThrow(
'Invalid password',
)
await expect(
shareService.verifyPublicAccess(symlink!.id, 'secret-password'),
).resolves.toBeDefined()
// Test expiration
await prisma.shareLink.update({
where: { id: shareLink.id },
data: { expireAt: new Date(Date.now() - 1000) },
})
await expect(shareService.verifyPublicAccess(symlink!.id, 'secret-password')).rejects.toThrow(
'expired',
)
})
it('traces deep ancestors for public access', async () => {
const shareLink = await shareService.createShareLink(projectId, {
name: 'Deep Share',
})
const subfolder = await prisma.asset.create({
data: {
name: 'subfolder',
type: AssetType.folder,
status: 'processed',
projectId,
parentId: shareLink.rootFolderId,
},
})
const deepFile = await prisma.asset.create({
data: {
name: 'deep.txt',
type: AssetType.file,
status: 'processed',
projectId,
parentId: subfolder.id,
},
})
await expect(shareService.verifyPublicAccess(deepFile.id)).resolves.toBeDefined()
})
it('verifies public access via symlink to a folder', async () => {
// 1. Create a real folder with a file
const realFolder = await prisma.asset.create({
data: {
name: 'Real Folder',
type: AssetType.folder,
status: 'processed',
projectId,
},
})
const realFile = await prisma.asset.create({
data: {
name: 'Real File',
type: AssetType.file,
status: 'processed',
projectId,
parentId: realFolder.id,
},
})
// 2. Share the folder via symlink
const shareLink = await shareService.createShareLink(projectId, { name: 'Folder Share' })
await shareService.addAssetToShare(shareLink.id, { assetIds: [realFolder.id] })
// 3. Verify access to the file inside the real folder (which is reached via the symlinked folder)
await expect(shareService.verifyPublicAccess(realFile.id)).resolves.toBeDefined()
})
it('fails public access for non-shared assets', async () => {
const privateFile = await prisma.asset.create({
data: {
name: 'private.txt',
type: AssetType.file,
status: 'processed',
projectId,
},
})
await expect(shareService.verifyPublicAccess(privateFile.id)).rejects.toThrow(
'Asset is not shared',
)
})
it('updates a share link including fieldVisibility', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'Old Name' })
const updated = await shareService.updateShareLink(shareLink.id, {
name: 'New Name',
password: 'new-password',
fieldVisibility: { field1: true, field2: false },
})
expect(updated.name).toBe('New Name')
expect(updated.hasPassword).toBe(true)
expect(updated.fieldVisibility).toEqual({ field1: true, field2: false })
const rootAsset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
expect(rootAsset?.name).toBe('New Name')
})
it('deletes a share link', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'To Delete' })
await shareService.deleteShareLink(shareLink.id)
const link = await prisma.shareLink.findUnique({ where: { id: shareLink.id } })
expect(link).toBeNull()
const asset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
expect(asset).toBeNull()
})
it('lists share links for a project', async () => {
await shareService.createShareLink(projectId, { name: 'Share 1' })
await shareService.createShareLink(projectId, { name: 'Share 2' })
const list = await shareService.listProjectShareLinks({ projectId })
expect(list.data).toHaveLength(2)
})
it('gets a single share link', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'Target' })
const fetched = await shareService.getShareLink(shareLink.id)
expect(fetched.name).toBe('Target')
})
it('removes an asset from share', async () => {
const file = await prisma.asset.create({
data: { name: 'f', type: AssetType.file, status: 'processed', projectId },
})
const shareLink = await shareService.createShareLink(projectId, { name: 'S' })
await shareService.addAssetToShare(shareLink.id, { assetIds: [file.id] })
const symlink = await prisma.asset.findFirst({ where: { targetId: file.id } })
expect(symlink).toBeDefined()
await shareService.removeAssetFromShare(shareLink.id, symlink!.id)
const symlinkAfter = await prisma.asset.findUnique({ where: { id: symlink!.id } })
expect(symlinkAfter).toBeNull()
})
})
+302
View File
@@ -0,0 +1,302 @@
import { prisma } from '@shumai/db'
import { AssetType, Prisma } from '@shumai/db'
import {
ShareLinkInfo,
CreateShareLinkRequest,
UpdateShareLinkRequest,
ListShareLinksRequest,
AddAssetToShareRequest,
} from '@shumai/dtos'
import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
export class ShareService {
async createShareLink(projectId: string, req: CreateShareLinkRequest): Promise<ShareLinkInfo> {
let project = await prisma.project.findUnique({
where: { id: projectId },
include: { shareRoot: true },
})
if (!project) throw new Error('Project not found')
// Lazy create share root if missing (for existing projects)
if (!project.shareRootId) {
const shareRootFolder = await prisma.asset.create({
data: {
name: 'share_root',
type: AssetType.share_root,
status: 'processed',
projectId: projectId,
},
})
project = await prisma.project.update({
where: { id: projectId },
data: { shareRootId: shareRootFolder.id },
include: { shareRoot: true },
})
}
return await prisma.$transaction(async (tx) => {
const shareFolder = await tx.asset.create({
data: {
name: req.name,
type: AssetType.share,
status: 'processed',
projectId: projectId,
parentId: project.shareRootId,
},
})
const shareLink = await tx.shareLink.create({
data: {
name: req.name,
expireAt: req.expireAt ? new Date(req.expireAt) : null,
password: req.password,
isDisabled: req.isDisabled ?? false,
defaultSortOrder: req.defaultSortOrder,
projectId: projectId,
rootFolderId: shareFolder.id,
},
})
return this.toShareLinkInfo(shareLink)
})
}
async updateShareLink(shareLinkId: string, req: UpdateShareLinkRequest): Promise<ShareLinkInfo> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
const updated = await prisma.shareLink.update({
where: { id: shareLinkId },
data: {
name: req.name,
expireAt:
req.expireAt !== undefined ? (req.expireAt ? new Date(req.expireAt) : null) : undefined,
password: req.password,
isDisabled: req.isDisabled,
defaultSortOrder: req.defaultSortOrder,
fieldVisibility: (req.fieldVisibility as PrismaJson.ShareLinkFieldVisibility) ?? undefined,
},
})
if (req.name) {
await prisma.asset.update({
where: { id: shareLink.rootFolderId },
data: { name: req.name },
})
}
return this.toShareLinkInfo(updated)
}
async deleteShareLink(shareLinkId: string): Promise<void> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
await prisma.$transaction(async (tx) => {
await tx.shareLink.delete({ where: { id: shareLinkId } })
// Delete the root folder asset, which should cascade to symlinks if set up correctly
// But Asset relation in prisma might not cascade delete children unless configured.
// Actually, targetId has onDelete: Cascade, but parentId doesn't necessarily.
// Let's manually delete the asset tree or ensure it's handled.
await tx.asset.delete({ where: { id: shareLink.rootFolderId } })
})
}
async listProjectShareLinks(req: ListShareLinksRequest): Promise<PaginatedData<ShareLinkInfo[]>> {
const where: Prisma.ShareLinkWhereInput = {
projectId: req.projectId,
}
return paginateQuery(
async (skip, take) => {
const links = await prisma.shareLink.findMany({
where,
skip,
take,
orderBy: { createdAt: 'desc' },
})
return links.map((l) => this.toShareLinkInfo(l))
},
() => prisma.shareLink.count({ where }),
req,
)
}
async getShareLink(shareLinkId: string): Promise<ShareLinkInfo> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
return this.toShareLinkInfo(shareLink)
}
async addAssetToShare(shareLinkId: string, req: AddAssetToShareRequest): Promise<number> {
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink) throw new Error('Share link not found')
const assetIds = req.assetIds
const existingSymlinks = await prisma.asset.findMany({
where: {
parentId: shareLink.rootFolderId,
targetId: { in: assetIds },
type: AssetType.symlink,
},
select: { targetId: true },
})
const existingTargetIds = new Set(existingSymlinks.map((s) => s.targetId))
const idsToAdd = assetIds.filter((id) => !existingTargetIds.has(id))
if (idsToAdd.length === 0) return 0
const targetAssets = await prisma.asset.findMany({
where: { id: { in: idsToAdd } },
})
const targetAssetMap = new Map(targetAssets.map((a) => [a.id, a]))
await prisma.$transaction(async (tx) => {
for (const assetId of idsToAdd) {
const targetAsset = targetAssetMap.get(assetId)
if (!targetAsset) continue
await tx.asset.create({
data: {
name: targetAsset.name,
type: AssetType.symlink,
status: 'processed',
projectId: shareLink.projectId,
parentId: shareLink.rootFolderId,
targetId: assetId,
},
})
}
await tx.asset.update({
where: { id: shareLink.rootFolderId },
data: { fileCount: { increment: idsToAdd.length } },
})
})
return idsToAdd.length
}
async removeAssetFromShare(shareLinkId: string, assetId: string): Promise<void> {
// Here assetId is the id of the symlink asset
const symlink = await prisma.asset.findUnique({
where: { id: assetId },
})
if (!symlink || symlink.type !== AssetType.symlink) {
throw new Error('Symlink not found')
}
const shareLink = await prisma.shareLink.findUnique({
where: { id: shareLinkId },
})
if (!shareLink || symlink.parentId !== shareLink.rootFolderId) {
throw new Error('Asset does not belong to this share link')
}
await prisma.$transaction(async (tx) => {
await tx.asset.delete({ where: { id: assetId } })
await tx.asset.update({
where: { id: shareLink.rootFolderId },
data: { fileCount: { decrement: 1 } },
})
})
}
async verifyPublicAccess(
assetId: string,
providedPassword?: string,
): Promise<Prisma.ShareLinkGetPayload<true>> {
// 1. Trace ancestors of the current asset in the real tree
// 2. Find if any ancestor (including itself) is the target of a symlink that belongs to a share
// 3. Or if the asset itself is a descendant of a 'share' type folder (direct share link root or subfolder within)
const rows = await prisma.$queryRaw<{ shareRootId: string }[]>`
WITH RECURSIVE
-- Trace ancestors in the real asset tree
real_ancestors AS (
SELECT id, parent_id, type::text FROM assets WHERE id = ${assetId}
UNION ALL
SELECT a.id, a.parent_id, a.type::text FROM assets a
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
),
-- Find all symlinks pointing to any of these real ancestors
found_symlinks AS (
SELECT s.id, s.parent_id, s.type::text FROM assets s
INNER JOIN real_ancestors ra ON s.target_id = ra.id
WHERE s.type = 'symlink'
),
-- Combine: start with either real ancestors that are 'share' type, or symlinks that lead to 'share' type
search_starts AS (
SELECT id, parent_id, type FROM real_ancestors WHERE type = 'share'
UNION
SELECT id, parent_id, type FROM found_symlinks
),
-- Trace UP from these search starts to find the ultimate 'share' root
share_trace AS (
SELECT id, parent_id, type FROM search_starts
UNION ALL
SELECT a.id, a.parent_id, a.type::text FROM assets a
INNER JOIN share_trace st ON st.parent_id = a.id
)
SELECT id as "shareRootId" FROM share_trace WHERE type = 'share' LIMIT 1;
`
if (rows.length === 0) {
throw new Error('Asset is not shared')
}
const shareRootId = rows[0].shareRootId
const shareLink = await prisma.shareLink.findUnique({
where: { rootFolderId: shareRootId },
})
if (!shareLink) {
throw new Error('Share link not found for this asset')
}
if (shareLink.isDisabled) {
throw new Error('Share link is disabled')
}
if (shareLink.expireAt && shareLink.expireAt < new Date()) {
throw new Error('Share link has expired')
}
if (shareLink.password && shareLink.password !== providedPassword) {
throw new Error('Invalid password for share link')
}
return shareLink
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private toShareLinkInfo(l: any): ShareLinkInfo {
const isExpired = l.expireAt ? new Date(l.expireAt) < new Date() : false
return {
id: l.id,
name: l.name,
expireAt: l.expireAt?.toISOString(),
isDisabled: l.isDisabled,
hasPassword: !!l.password,
defaultSortOrder: l.defaultSortOrder,
fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined,
rootFolderId: l.rootFolderId,
projectId: l.projectId,
isExpired,
createdAt: l.createdAt.toISOString(),
updatedAt: l.updatedAt.toISOString(),
}
}
}
export const shareService = new ShareService()