refactor(api): enforce layered architecture by moving db queries to core services

This commit is contained in:
yiling
2026-08-01 16:25:01 +08:00
parent fb66166b49
commit 97069042b2
26 changed files with 256 additions and 363 deletions
+4 -11
View File
@@ -11,22 +11,15 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
logAction: vi.fn().mockResolvedValue({}), logAction: vi.fn().mockResolvedValue({}),
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
agent: {
findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }),
},
},
}
})
describe('Agent API', () => { describe('Agent API', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
vi.mocked(agentService.getAgent).mockResolvedValue({
id: 'agent1',
teamId: 'team1',
} as unknown as Awaited<ReturnType<typeof agentService.getAgent>>)
}) })
describe('GET /teams/:teamId/agents', () => { describe('GET /teams/:teamId/agents', () => {
+1 -5
View File
@@ -13,7 +13,6 @@ import {
} from '@shumai/dtos' } from '@shumai/dtos'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -163,10 +162,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId, id: agentId,
}) })
const existingAgent = await prisma.agent.findUnique({ const existingAgent = await agentService.getAgent({ agentId })
where: { id: agentId },
select: { teamId: true },
})
await agentService.deleteAgent({ await agentService.deleteAgent({
agentId, agentId,
+5 -12
View File
@@ -19,24 +19,17 @@ vi.mock('./middleware/auth', () => ({
vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/asset/asset') vi.mock('@shumai/core/src/asset/asset')
vi.mock('@shumai/core/src/project/project', () => ({
projectService: {
getProjectTeam: vi.fn().mockResolvedValue('t1'),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: { auditLogService: {
logAction: vi.fn().mockResolvedValue({}), logAction: vi.fn().mockResolvedValue({}),
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
project: {
findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }),
},
},
}
})
vi.mock('@shumai/core/src/s3/s3', () => ({ vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: { s3Service: {
presign: vi.fn().mockResolvedValue('http://mock-s3-url'), presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
+5 -7
View File
@@ -4,7 +4,8 @@ import { postAttachmentRequestSchema, AuditAction } from '@shumai/dtos'
import { assetService } from '@shumai/core/src/asset/asset' import { assetService } from '@shumai/core/src/asset/asset'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { AssetType, prisma } from '@shumai/db' import { projectService } from '@shumai/core/src/project/project'
import { AssetType } from '@shumai/db'
import { ulid } from 'ulid' import { ulid } from 'ulid'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
@@ -38,14 +39,11 @@ const route = new Hono<{ Variables: { user: User } }>().post(
creatorId: user.id, creatorId: user.id,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.file_create, action: AuditAction.file_create,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: assetInfo.id, itemId: assetInfo.id,
+5 -8
View File
@@ -1,9 +1,9 @@
import { Hono } from 'hono' import { Hono } from 'hono'
import { teamService } from '@shumai/core/src/team/team' import { teamService } from '@shumai/core/src/team/team'
import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { z } from 'zod' import { z } from 'zod'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { prisma } from '@shumai/db'
import { ulid } from 'ulid' import { ulid } from 'ulid'
const app = new Hono() const app = new Hono()
@@ -31,13 +31,10 @@ const route = app
const { username, email } = c.req.valid('json') const { username, email } = c.req.valid('json')
const dummyEmail = `guest_${ulid()}@guest.local` const dummyEmail = `guest_${ulid()}@guest.local`
const user = await prisma.user.create({ const user = await userService.createGuestUser({
data: { name: username,
name: username, email: dummyEmail,
email: dummyEmail, guestEmail: email,
guestEmail: email,
type: 'human',
},
}) })
return c.json({ id: user.id }) return c.json({ id: user.id })
+3 -5
View File
@@ -1,6 +1,5 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono' import { Hono, type Context, type Next } from 'hono'
import { prisma } from '@shumai/db'
import fileRoute from './file' import fileRoute from './file'
import { assetService } from '@shumai/core/src/asset/asset' import { assetService } from '@shumai/core/src/asset/asset'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
@@ -66,6 +65,7 @@ describe('file api', () => {
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'completeComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn()) vi.spyOn(assetService, 'deleteComment').mockImplementation(vi.fn())
vi.spyOn(assetService, 'getComment').mockResolvedValue({ id: 'comment1', assetId: 'file1' } as any)
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn()) vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn()) vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn()) vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
@@ -278,9 +278,9 @@ describe('file api', () => {
project: { teamId: 'test-team' }, project: { teamId: 'test-team' },
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const mockFindUnique = vi.spyOn(prisma.assetComment, 'findUnique').mockResolvedValue({ vi.mocked(assetService.getComment).mockResolvedValue({
id: 'parent-comment-id', id: 'parent-comment-id',
creatorId: 'parent-comment-creator-id', creator: { id: 'parent-comment-creator-id' },
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any } as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const app = new Hono().use('*', authMiddleware).route('/', fileRoute) const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
@@ -306,8 +306,6 @@ describe('file api', () => {
userId: 'parent-comment-creator-id', userId: 'parent-comment-creator-id',
commentMessage: 'hello reply', commentMessage: 'hello reply',
}) })
mockFindUnique.mockRestore()
}) })
it('GET /files/:fileId/comments', async () => { it('GET /files/:fileId/comments', async () => {
+5 -14
View File
@@ -5,7 +5,6 @@ import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification' import { notificationService } from '@shumai/core/src/notification/notification'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { import {
createCommentRequestSchema, createCommentRequestSchema,
@@ -187,11 +186,9 @@ const route = new Hono<{ Variables: { user: User } }>()
let targetUserId: string | undefined let targetUserId: string | undefined
if (req.replyToId) { if (req.replyToId) {
const parentComment = await prisma.assetComment.findUnique({ const parentComment = await assetService.getComment(req.replyToId).catch(() => null)
where: { id: req.replyToId }, if (parentComment?.creator?.id) {
}) targetUserId = parentComment.creator.id
if (parentComment?.creatorId) {
targetUserId = parentComment.creatorId
} }
} }
@@ -245,10 +242,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: commentId, id: commentId,
}) })
const commentData = await prisma.assetComment.findUnique({ const commentData = await assetService.getComment(commentId).catch(() => null)
where: { id: commentId },
select: { assetId: true },
})
const updated = await assetService.completeComment(commentId, req.isCompleted, user.id) const updated = await assetService.completeComment(commentId, req.isCompleted, user.id)
@@ -277,10 +271,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id: commentId, id: commentId,
}) })
const commentData = await prisma.assetComment.findUnique({ const commentData = await assetService.getComment(commentId).catch(() => null)
where: { id: commentId },
select: { assetId: true },
})
await assetService.deleteComment({ commentId, userId: user.id }) await assetService.deleteComment({ commentId, userId: user.id })
+5 -11
View File
@@ -18,22 +18,16 @@ vi.mock('./middleware/auth', () => ({
vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/metadata/metadata') vi.mock('@shumai/core/src/metadata/metadata')
vi.mock('@shumai/core/src/project/project', () => ({
projectService: {
getProjectTeam: vi.fn().mockResolvedValue('t1'),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: { auditLogService: {
logAction: vi.fn().mockResolvedValue({}), logAction: vi.fn().mockResolvedValue({}),
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
project: {
findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }),
},
},
}
})
describe('metadata api', () => { describe('metadata api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+6 -17
View File
@@ -1,6 +1,7 @@
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono' import { Hono } from 'hono'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
import { projectService } from '@shumai/core/src/project/project'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { import {
createFieldRequestSchema, createFieldRequestSchema,
@@ -10,7 +11,6 @@ import {
AuditAction, AuditAction,
} from '@shumai/dtos' } from '@shumai/dtos'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -98,11 +98,7 @@ const route = new Hono<{ Variables: { user: User } }>()
let teamId = field.teamId let teamId = field.teamId
if (field.projectId && !teamId) { if (field.projectId && !teamId) {
const proj = await prisma.project.findUnique({ teamId = await projectService.getProjectTeam(field.projectId).catch(() => null)
where: { id: field.projectId },
select: { teamId: true },
})
teamId = proj?.teamId || null
} }
if (teamId) { if (teamId) {
@@ -141,11 +137,7 @@ const route = new Hono<{ Variables: { user: User } }>()
let teamId = field.teamId let teamId = field.teamId
if (field.projectId && !teamId) { if (field.projectId && !teamId) {
const proj = await prisma.project.findUnique({ teamId = await projectService.getProjectTeam(field.projectId).catch(() => null)
where: { id: field.projectId },
select: { teamId: true },
})
teamId = proj?.teamId || null
} }
if (teamId) { if (teamId) {
@@ -174,15 +166,12 @@ const route = new Hono<{ Variables: { user: User } }>()
const field = await metadataService.createProjectField(projectId, req) const field = await metadataService.createProjectField(projectId, req)
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId },
select: { teamId: true },
})
if (proj) { if (teamId) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.metadata_field_create, action: AuditAction.metadata_field_create,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: field.key, itemId: field.key,
+20 -26
View File
@@ -2,7 +2,8 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono } from 'hono'
import { authMiddleware } from './auth' import { authMiddleware } from './auth'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db' import { userService } from '@shumai/core/src/user/user'
import { teamService } from '@shumai/core/src/team/team'
vi.mock('@shumai/core/src/auth/auth', () => ({ vi.mock('@shumai/core/src/auth/auth', () => ({
auth: { auth: {
@@ -12,14 +13,15 @@ vi.mock('@shumai/core/src/auth/auth', () => ({
}, },
})) }))
vi.mock('@shumai/db', () => ({ vi.mock('@shumai/core/src/user/user', () => ({
prisma: { userService: {
user: { getUserById: vi.fn(),
findUnique: vi.fn(), },
}, }))
teamMember: {
findFirst: vi.fn(), vi.mock('@shumai/core/src/team/team', () => ({
}, teamService: {
hasWritableRoleInAnyTeam: vi.fn(),
}, },
})) }))
@@ -39,7 +41,7 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test') const res = await app.request('/test')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -61,7 +63,7 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test') const res = await app.request('/test')
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -71,8 +73,8 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue(null) // No owner/editor role vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(false) // No owner/editor role
const res = await app.request('/test', { method: 'POST' }) const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(403) expect(res.status).toBe(403)
@@ -83,7 +85,7 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test/search', { method: 'POST' }) const res = await app.request('/test/search', { method: 'POST' })
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -93,12 +95,8 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({ vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true)
id: 'member1',
role: 'owner',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { method: 'POST' }) const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(200) expect(res.status).toBe(200)
@@ -108,12 +106,8 @@ describe('authMiddleware', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any) vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any) vi.mocked(userService.getUserById).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({ vi.mocked(teamService.hasWritableRoleInAnyTeam).mockResolvedValue(true)
id: 'member1',
role: 'editor',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { method: 'POST' }) const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(200) expect(res.status).toBe(200)
+5 -11
View File
@@ -1,6 +1,7 @@
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db' import { userService } from '@shumai/core/src/user/user'
import { teamService } from '@shumai/core/src/team/team'
import { createMiddleware } from 'hono/factory' import { createMiddleware } from 'hono/factory'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -24,9 +25,7 @@ export const authMiddleware = createMiddleware<{
} }
try { try {
const user = await prisma.user.findUnique({ const user = await userService.getUserById(session.user.id)
where: { id: session.user.id },
})
if (!user) { if (!user) {
return c.json({ error: 'User not found' }, 401) return c.json({ error: 'User not found' }, 401)
@@ -38,14 +37,9 @@ export const authMiddleware = createMiddleware<{
const method = c.req.method.toUpperCase() const method = c.req.method.toUpperCase()
const path = c.req.path const path = c.req.path
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) { if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) {
const member = await prisma.teamMember.findFirst({ const hasWritable = await teamService.hasWritableRoleInAnyTeam(user.id)
where: {
userId: user.id,
role: { in: ['owner', 'editor'] },
},
})
if (!member) { if (!hasWritable) {
return c.json({ error: 'System is in read-only mode' }, 403) return c.json({ error: 'System is in read-only mode' }, 403)
} }
} }
+17 -41
View File
@@ -1,13 +1,12 @@
import { describe, expect, it, vi, beforeEach } from 'vitest' import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono' import { Hono } from 'hono'
import { tokenAuthMiddleware } from './tokenAuth' import { tokenAuthMiddleware } from './tokenAuth'
import { prisma } from '@shumai/db' import { apiTokenService } from '@shumai/core/src/user/api-token'
import type { Prisma } from '@shumai/db'
vi.mock('@shumai/db', () => ({ vi.mock('@shumai/core/src/user/api-token', () => ({
prisma: { apiTokenService: {
apiToken: { validateToken: vi.fn(),
findUnique: vi.fn(),
},
}, },
})) }))
@@ -31,21 +30,11 @@ describe('tokenAuthMiddleware', () => {
}) })
it('sets user when valid Authorization Bearer token is provided', async () => { it('sets user when valid Authorization Bearer token is provided', async () => {
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({ vi.mocked(apiTokenService.validateToken).mockResolvedValue({
id: 'token1', id: 'user123',
token: 'ulid_token_123', name: 'John Doe',
name: 'cli-key', email: 'john@example.com',
userId: 'user123', } as unknown as Prisma.UserGetPayload<Record<string, never>>)
createdAt: new Date(),
updatedAt: new Date(),
user: {
id: 'user123',
name: 'John Doe',
email: 'john@example.com',
},
// Mocking the complex PrismaPromise return type of findUnique is not feasible without any here.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { const res = await app.request('/test', {
headers: { headers: {
@@ -54,28 +43,15 @@ describe('tokenAuthMiddleware', () => {
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.text()).toBe('user:user123') expect(await res.text()).toBe('user:user123')
expect(prisma.apiToken.findUnique).toHaveBeenCalledWith({ expect(apiTokenService.validateToken).toHaveBeenCalledWith('ulid_token_123')
where: { token: 'ulid_token_123' },
include: { user: true },
})
}) })
it('sets user when valid x-api-key header is provided', async () => { it('sets user when valid x-api-key header is provided', async () => {
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({ vi.mocked(apiTokenService.validateToken).mockResolvedValue({
id: 'token1', id: 'user123',
token: 'ulid_token_123', name: 'John Doe',
name: 'cli-key', email: 'john@example.com',
userId: 'user123', } as unknown as Prisma.UserGetPayload<Record<string, never>>)
createdAt: new Date(),
updatedAt: new Date(),
user: {
id: 'user123',
name: 'John Doe',
email: 'john@example.com',
},
// Mocking the complex PrismaPromise return type of findUnique is not feasible without any here.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { const res = await app.request('/test', {
headers: { headers: {
@@ -87,7 +63,7 @@ describe('tokenAuthMiddleware', () => {
}) })
it('returns 401 when invalid token is provided', async () => { it('returns 401 when invalid token is provided', async () => {
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue(null) vi.mocked(apiTokenService.validateToken).mockResolvedValue(null)
const res = await app.request('/test', { const res = await app.request('/test', {
headers: { headers: {
+4 -7
View File
@@ -1,5 +1,5 @@
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db' import { apiTokenService } from '@shumai/core/src/user/api-token'
import { createMiddleware } from 'hono/factory' import { createMiddleware } from 'hono/factory'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -16,16 +16,13 @@ export const tokenAuthMiddleware = createMiddleware<{
: c.req.header('x-api-key') || null : c.req.header('x-api-key') || null
if (token) { if (token) {
const apiToken = await prisma.apiToken.findUnique({ const user = await apiTokenService.validateToken(token)
where: { token },
include: { user: true },
})
if (!apiToken) { if (!user) {
return c.json({ error: 'Unauthorized: Invalid API Key' }, 401) return c.json({ error: 'Unauthorized: Invalid API Key' }, 401)
} }
c.set('user', apiToken.user) c.set('user', user)
} }
await next() await next()
+24 -44
View File
@@ -5,6 +5,7 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
import { projectService } from '@shumai/core/src/project/project' import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset' import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import type { ProjectInfo } from '@shumai/dtos'
vi.mock('./middleware/auth', () => ({ vi.mock('./middleware/auth', () => ({
authMiddleware: async ( authMiddleware: async (
@@ -17,7 +18,22 @@ vi.mock('./middleware/auth', () => ({
})) }))
vi.mock('@shumai/core/src/authz/authz') vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/project/project') vi.mock('@shumai/core/src/project/project', () => ({
projectService: {
createProject: vi.fn(),
updateProject: vi.fn(),
getProject: vi.fn(),
getProjectTeam: vi.fn().mockResolvedValue('t1'),
deleteProject: vi.fn(),
listProjects: vi.fn(),
getUserProjects: vi.fn(),
listProjectMembers: vi.fn(),
addProjectMember: vi.fn(),
updateMemberRole: vi.fn(),
removeMember: vi.fn(),
getProjectMe: vi.fn(),
},
}))
vi.mock('@shumai/core/src/asset/asset') vi.mock('@shumai/core/src/asset/asset')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: { auditLogService: {
@@ -25,21 +41,6 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
listAuditLogs: vi.fn().mockResolvedValue({ nodes: [], pageInfo: {}, total: 0 }), listAuditLogs: vi.fn().mockResolvedValue({ nodes: [], pageInfo: {}, total: 0 }),
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
teamMember: {
findMany: vi.fn(),
},
project: {
findMany: vi.fn(),
findUnique: vi.fn(),
},
},
}
})
describe('project api', () => { describe('project api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
@@ -163,10 +164,7 @@ describe('project api', () => {
}) })
it('POST /projects/:projectId/reparent', async () => { it('POST /projects/:projectId/reparent', async () => {
const { prisma } = await import('@shumai/db') vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1')
// Mocking partial Prisma project model in test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any)
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined) vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
const res = await app.request('/projects/p/reparent', { const res = await app.request('/projects/p/reparent', {
@@ -219,10 +217,7 @@ describe('project api', () => {
}) })
it('POST /projects/:projectId/copy', async () => { it('POST /projects/:projectId/copy', async () => {
const { prisma } = await import('@shumai/db') vi.mocked(projectService.getProjectTeam).mockResolvedValue('t1')
// Mocking partial Prisma project model in test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any)
vi.mocked(assetService.copyAssets).mockResolvedValue(undefined) vi.mocked(assetService.copyAssets).mockResolvedValue(undefined)
const res = await app.request('/projects/p/copy', { const res = await app.request('/projects/p/copy', {
@@ -320,24 +315,16 @@ describe('project api', () => {
}) })
it('GET /projects', async () => { it('GET /projects', async () => {
const { prisma } = await import('@shumai/db') vi.mocked(projectService.getUserProjects).mockResolvedValue([
vi.mocked(prisma.teamMember.findMany).mockResolvedValue([
{ id: 'tm1', teamId: 'team1', userId: 'user1', scope: 'team' },
// Mocking complex Prisma client returns requires any here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
vi.mocked(prisma.project.findMany).mockResolvedValue([
{ {
id: 'proj1', id: 'proj1',
name: 'My Project', name: 'My Project',
teamId: 'team1', teamId: 'team1',
rootFolderId: 'folder1', rootFolder: 'folder1',
enableNotification: true, enableNotification: true,
updatedAt: new Date('2026-06-21T00:00:00.000Z'), updatedAt: '2026-06-21T00:00:00.000Z',
}, },
// Mocking complex Prisma client returns requires any here ] as unknown as ProjectInfo[])
// eslint-disable-next-line @typescript-eslint/no-explicit-any
] as any)
const res = await app.request('/projects?first=10') const res = await app.request('/projects?first=10')
@@ -352,13 +339,6 @@ describe('project api', () => {
enableNotification: true, enableNotification: true,
updatedAt: '2026-06-21T00:00:00.000Z', updatedAt: '2026-06-21T00:00:00.000Z',
}) })
expect(prisma.teamMember.findMany).toHaveBeenCalledWith({ expect(projectService.getUserProjects).toHaveBeenCalledWith('user1', 10)
where: { userId: 'user1' },
})
expect(prisma.project.findMany).toHaveBeenCalledWith({
where: { teamId: 'team1' },
orderBy: { id: 'desc' },
take: 10,
})
}) })
}) })
+26 -77
View File
@@ -14,7 +14,6 @@ import {
} from '@shumai/dtos' } from '@shumai/dtos'
import { listMembersQuerySchema, paginationParamsSchema, AuditAction } from '@shumai/dtos' import { listMembersQuerySchema, paginationParamsSchema, AuditAction } from '@shumai/dtos'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -25,41 +24,16 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('query') const req = c.req.valid('query')
const limit = req.first ? Math.min(req.first, 200) : 200 const limit = req.first ? Math.min(req.first, 200) : 200
const teamMembers = await prisma.teamMember.findMany({ const allProjects = await projectService.getUserProjects(user.id, limit)
where: { userId: user.id },
})
type ProjectType = Prisma.ProjectGetPayload<Record<string, never>>
const allProjects: ProjectType[] = []
for (const member of teamMembers) {
const where: Prisma.ProjectWhereInput = {
teamId: member.teamId,
}
if (member.scope === 'project') {
where.members = {
some: { teamMemberId: member.id },
}
}
const teamProjects = await prisma.project.findMany({
where,
orderBy: { id: 'desc' },
take: limit - allProjects.length,
})
allProjects.push(...teamProjects)
if (allProjects.length >= limit) {
break
}
}
return c.json({ return c.json({
data: allProjects.map((p) => ({ data: allProjects.map((p) => ({
id: p.id, id: p.id,
name: p.name, name: p.name,
teamId: p.teamId, teamId: p.teamId,
rootFolder: p.rootFolderId || undefined, rootFolder: p.rootFolder,
enableNotification: p.enableNotification, enableNotification: p.enableNotification,
updatedAt: p.updatedAt.toISOString(), updatedAt: p.updatedAt,
})), })),
}) })
}) })
@@ -107,14 +81,10 @@ const route = new Hono<{ Variables: { user: User } }>()
...req, ...req,
}) })
const proj = await prisma.project.findUnique({ if (updatedProject) {
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_update, action: AuditAction.project_update,
teamId: proj.teamId, teamId: updatedProject.teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: projectId, itemId: projectId,
@@ -161,14 +131,11 @@ const route = new Hono<{ Variables: { user: User } }>()
await assetService.emptyTrash(projectId) await assetService.emptyTrash(projectId)
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_empty_trash, action: AuditAction.project_empty_trash,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: projectId, itemId: projectId,
@@ -230,16 +197,13 @@ const route = new Hono<{ Variables: { user: User } }>()
id: projectId, id: projectId,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId },
select: { teamId: true },
})
await projectService.deleteProject(projectId) await projectService.deleteProject(projectId)
if (proj) { if (teamId) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_delete, action: AuditAction.project_delete,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: projectId, itemId: projectId,
@@ -326,15 +290,12 @@ const route = new Hono<{ Variables: { user: User } }>()
creatorId: user.id, creatorId: user.id,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
for (const assetId of req.assetIds) { for (const assetId of req.assetIds) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.asset_reparent, action: AuditAction.asset_reparent,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: assetId, itemId: assetId,
@@ -373,15 +334,12 @@ const route = new Hono<{ Variables: { user: User } }>()
creatorId: user.id, creatorId: user.id,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
for (const assetId of req.assetIds) { for (const assetId of req.assetIds) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.asset_copy, action: AuditAction.asset_copy,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: assetId, itemId: assetId,
@@ -413,14 +371,11 @@ const route = new Hono<{ Variables: { user: User } }>()
role: req.role, role: req.role,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_member_update, action: AuditAction.project_member_update,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: userId, itemId: userId,
@@ -442,16 +397,13 @@ const route = new Hono<{ Variables: { user: User } }>()
id: projectId, id: projectId,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId },
select: { teamId: true },
})
await projectService.removeMember(projectId, userId) await projectService.removeMember(projectId, userId)
if (proj) { if (teamId) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_member_remove, action: AuditAction.project_member_remove,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: userId, itemId: userId,
@@ -481,14 +433,11 @@ const route = new Hono<{ Variables: { user: User } }>()
role: req.role, role: req.role,
}) })
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.project_member_add, action: AuditAction.project_member_add,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: req.userId, itemId: req.userId,
+5 -13
View File
@@ -8,8 +8,9 @@ import { z } from 'zod'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
import { FieldInfo } from '@shumai/dtos' import { FieldInfo } from '@shumai/dtos'
import type { Prisma as PrismaType } from '@shumai/db' import type { Prisma as PrismaType } from '@shumai/db'
import { projectService } from '@shumai/core/src/project/project'
import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db'
import { createCommentRequestSchema } from '@shumai/dtos' import { createCommentRequestSchema } from '@shumai/dtos'
import { notificationService } from '@shumai/core/src/notification/notification' import { notificationService } from '@shumai/core/src/notification/notification'
import { import {
@@ -204,14 +205,7 @@ const route = app
const targetFileId = await assetService.resolveTargetAssetId(fileId) const targetFileId = await assetService.resolveTargetAssetId(fileId)
const project = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(shareLink.projectId)
where: { id: shareLink.projectId },
select: { teamId: true },
})
if (!project) {
throw new Error('Project not found')
}
// Identify user // Identify user
let userId: string | null = null let userId: string | null = null
@@ -222,9 +216,7 @@ const route = app
if (session?.user) { if (session?.user) {
userId = session.user.id userId = session.user.id
} else if (guestUserId) { } else if (guestUserId) {
const guestUser = await prisma.user.findUnique({ const guestUser = await userService.getUserById(guestUserId)
where: { id: guestUserId },
})
if (guestUser) { if (guestUser) {
userId = guestUser.id userId = guestUser.id
} }
@@ -248,7 +240,7 @@ const route = app
notificationService.create({ notificationService.create({
type: notifType, type: notifType,
teamId: project.teamId, teamId: teamId,
creatorId: userId, creatorId: userId,
assetId: targetFileId, assetId: targetFileId,
commentMessage: req.message, commentMessage: req.message,
+5 -11
View File
@@ -41,17 +41,11 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => { vi.mock('@shumai/core/src/project/project', () => ({
const actual = await importOriginal<typeof import('@shumai/db')>() projectService: {
return { getProjectTeam: vi.fn().mockResolvedValue('t1'),
...actual, },
prisma: { }))
project: {
findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }),
},
},
}
})
describe('Share API', () => { describe('Share API', () => {
const app = new Hono() const app = new Hono()
+10 -19
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { shareService } from '@shumai/core/src/share/share' import { shareService } from '@shumai/core/src/share/share'
import { projectService } from '@shumai/core/src/project/project'
import { import {
createShareLinkRequestSchema, createShareLinkRequestSchema,
updateShareLinkRequestSchema, updateShareLinkRequestSchema,
@@ -10,7 +11,6 @@ import {
AuditAction, AuditAction,
} from '@shumai/dtos' } from '@shumai/dtos'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -33,14 +33,11 @@ const route = new Hono<{ Variables: { user: User } }>()
const shareLink = await shareService.createShareLink(projectId, req, user.id) const shareLink = await shareService.createShareLink(projectId, req, user.id)
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(projectId).catch(() => null)
where: { id: projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.share_create, action: AuditAction.share_create,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId, projectId,
itemId: shareLink.id, itemId: shareLink.id,
@@ -103,14 +100,11 @@ const route = new Hono<{ Variables: { user: User } }>()
const updated = await shareService.updateShareLink(shareId, req) const updated = await shareService.updateShareLink(shareId, req)
if (existingShare) { if (existingShare) {
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(existingShare.projectId).catch(() => null)
where: { id: existingShare.projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.share_update, action: AuditAction.share_update,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId: existingShare.projectId, projectId: existingShare.projectId,
itemId: shareId, itemId: shareId,
@@ -135,14 +129,11 @@ const route = new Hono<{ Variables: { user: User } }>()
await shareService.deleteShareLink(shareId) await shareService.deleteShareLink(shareId)
if (existingShare) { if (existingShare) {
const proj = await prisma.project.findUnique({ const teamId = await projectService.getProjectTeam(existingShare.projectId).catch(() => null)
where: { id: existingShare.projectId }, if (teamId) {
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({ await auditLogService.logAction({
action: AuditAction.share_delete, action: AuditAction.share_delete,
teamId: proj.teamId, teamId,
userId: user.id, userId: user.id,
projectId: existingShare.projectId, projectId: existingShare.projectId,
itemId: shareId, itemId: shareId,
+14 -11
View File
@@ -13,17 +13,16 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
}, },
})) }))
vi.mock('@shumai/db', async (importOriginal) => { vi.mock('@shumai/core/src/skill/skill', () => ({
const actual = await importOriginal<typeof import('@shumai/db')>() skillService: {
return { listSkills: vi.fn(),
...actual, upsertSkill: vi.fn(),
prisma: { deleteSkill: vi.fn(),
skill: { updateSkillConfig: vi.fn(),
findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }), updateSkillPermission: vi.fn(),
}, getSkill: vi.fn().mockResolvedValue({ id: 'skill1', teamId: 'team1' }),
}, },
} }))
})
vi.mock('./middleware/auth', () => ({ vi.mock('./middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -55,6 +54,10 @@ describe('Skill API', () => {
beforeEach(() => { beforeEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
vi.mocked(skillService.getSkill).mockResolvedValue({
id: 'skill1',
teamId: 'team1',
} as unknown as Awaited<ReturnType<typeof skillService.getSkill>>)
}) })
describe('GET /teams/:teamId/skills', () => { describe('GET /teams/:teamId/skills', () => {
+3 -13
View File
@@ -9,7 +9,6 @@ import {
AuditAction, AuditAction,
} from '@shumai/dtos' } from '@shumai/dtos'
import type { Prisma } from '@shumai/db' import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>> type User = Prisma.UserGetPayload<Record<string, never>>
@@ -68,10 +67,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id, id,
}) })
const existingSkill = await prisma.skill.findUnique({ const existingSkill = await skillService.getSkill(id)
where: { id },
select: { teamId: true },
})
await skillService.deleteSkill(id) await skillService.deleteSkill(id)
@@ -98,10 +94,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id, id,
}) })
const existingSkill = await prisma.skill.findUnique({ const existingSkill = await skillService.getSkill(id)
where: { id },
select: { teamId: true },
})
const skill = await skillService.updateSkillConfig(id, req.config) const skill = await skillService.updateSkillConfig(id, req.config)
@@ -131,10 +124,7 @@ const route = new Hono<{ Variables: { user: User } }>()
id, id,
}) })
const existingSkill = await prisma.skill.findUnique({ const existingSkill = await skillService.getSkill(id)
where: { id },
select: { teamId: true },
})
const skill = await skillService.updateSkillPermission(id, req.permission) const skill = await skillService.updateSkillPermission(id, req.permission)
+6
View File
@@ -300,6 +300,12 @@ export class AgentService {
}) })
} }
async getAgent(params: { agentId: string }) {
return this.prismaClient.agent.findUnique({
where: { id: params.agentId },
})
}
async deleteAgent(params: DeleteAgentParams) { async deleteAgent(params: DeleteAgentParams) {
const { agentId } = params const { agentId } = params
+1
View File
@@ -17,6 +17,7 @@ export * from './transcode/transcode'
export * from './upload/upload' export * from './upload/upload'
export * from './user-metadata/user-metadata' export * from './user-metadata/user-metadata'
export * from './user/avatar' export * from './user/avatar'
export * from './user/user'
export * from './versionStack/versionStack' export * from './versionStack/versionStack'
export * from './hyrumtoken' export * from './hyrumtoken'
export * from './pagination' export * from './pagination'
+32
View File
@@ -160,6 +160,38 @@ export class ProjectService {
return res return res
} }
async getUserProjects(userId: string, limit = 200): Promise<ProjectInfo[]> {
const teamMembers = await prisma.teamMember.findMany({
where: { userId },
})
const allProjects: ProjectInfo[] = []
for (const member of teamMembers) {
const where: Prisma.ProjectWhereInput = {
teamId: member.teamId,
}
if (member.scope === 'project') {
where.members = {
some: { teamMemberId: member.id },
}
}
const teamProjects = await prisma.project.findMany({
where,
orderBy: { id: 'desc' },
take: limit - allProjects.length,
include: { rootFolder: true },
})
const infos = await Promise.all(teamProjects.map((p) => this.toProjectInfo(p)))
allProjects.push(...infos)
if (allProjects.length >= limit) {
break
}
}
return allProjects
}
async addProjectMember(req: ServiceAddProjectMemberRequest): Promise<void> { async addProjectMember(req: ServiceAddProjectMemberRequest): Promise<void> {
const user = await prisma.user.findUnique({ where: { id: req.userId } }) const user = await prisma.user.findUnique({ where: { id: req.userId } })
if (!user) throw new Error('User not found') if (!user) throw new Error('User not found')
+11
View File
@@ -275,6 +275,17 @@ export class SkillService {
return { name, description } return { name, description }
} }
async getSkill(id: string) {
const s = await this.prismaClient.skill.findUnique({
where: { id },
})
if (!s) return null
return {
...this.toSkillInfo(s),
teamId: s.teamId,
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
private toSkillInfo(s: any): SkillInfo { private toSkillInfo(s: any): SkillInfo {
return { return {
+10
View File
@@ -364,6 +364,16 @@ export class TeamService {
} }
} }
async hasWritableRoleInAnyTeam(userId: string): Promise<boolean> {
const member = await prisma.teamMember.findFirst({
where: {
userId,
role: { in: ['owner', 'editor'] },
},
})
return !!member
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
private toTeamInfo(team: any): TeamInfo { private toTeamInfo(team: any): TeamInfo {
return { return {
+24
View File
@@ -0,0 +1,24 @@
import { prisma } from '@shumai/db'
export class UserService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async getUserById(id: string) {
return this.prismaClient.user.findUnique({
where: { id },
})
}
async createGuestUser(data: { name: string; email: string; guestEmail: string }) {
return this.prismaClient.user.create({
data: {
name: data.name,
email: data.email,
guestEmail: data.guestEmail,
type: 'human',
},
})
}
}
export const userService = new UserService()