mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 16:19:20 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import app from './agent'
|
||||
|
||||
vi.mock('@/services/agent/agent')
|
||||
vi.mock('@/services/authz/authz')
|
||||
|
||||
describe('Agent API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agents', () => {
|
||||
it('returns list of agents', async () => {
|
||||
const mockAgents = [
|
||||
{
|
||||
id: 'agent1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Soul',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
thinkingLevel: 'high',
|
||||
systemPrompt: 'prompt',
|
||||
},
|
||||
skills: [],
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.listAgents).mockResolvedValue(mockAgents as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Bot 1')
|
||||
expect(data[0].providerId).toBe('prov1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/agents', () => {
|
||||
it('creates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent2',
|
||||
user: { name: 'New Agent', image: 'avatar2' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'New Soul',
|
||||
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.createAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Agent',
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
thinkingLevel: 'low',
|
||||
systemPrompt: 'p',
|
||||
soul: 'New Soul',
|
||||
skills: ['skill1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('New Agent')
|
||||
expect(data.soul).toBe('New Soul')
|
||||
})
|
||||
|
||||
it('validates request', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: '',
|
||||
type: 'chat',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /teams/:teamId/agents/:agentId', () => {
|
||||
it('updates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
user: { name: 'Updated Agent', image: 'avatar1' },
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
config: { provider: 'prov1', model: 'model1' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
skills: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('Updated Agent')
|
||||
expect(data.soul).toBe('Updated Soul')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/agents/:agentId', () => {
|
||||
it('deletes an agent', async () => {
|
||||
const res = await app.request('/teams/team1/agents/agent1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
} from '@/dtos/agent'
|
||||
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/agents', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
|
||||
const res: AgentInfo[] = agents.map((agent) => {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('failed to create agent')
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/agents/:agentId',
|
||||
zValidator('json', updateAgentRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/agents/:agentId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await agentService.deleteAgent({
|
||||
agentId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import attachmentRoute from './attachment'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { AssetType } from '@/generated/prisma/client'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Attachment API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', attachmentRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/attachments', async () => {
|
||||
// We only need the id for this test
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(assetService, 'createAsset').mockResolvedValue({ id: 'asset1' } as any)
|
||||
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileName: 'test.txt',
|
||||
contentType: 'text/plain',
|
||||
size: 100,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('asset1')
|
||||
expect(json.uploadUrl).toBe('http://mock-s3-url')
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'test.txt',
|
||||
type: AssetType.attachment,
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { postAttachmentRequestSchema } from '@/dtos/asset'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { AssetType } from '@/generated/prisma/client'
|
||||
import { ulid } from 'ulid'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
'/projects/:projectId/attachments',
|
||||
zValidator('json', postAttachmentRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
|
||||
const assetInfo = await assetService.createAsset({
|
||||
name: req.fileName,
|
||||
type: AssetType.attachment,
|
||||
projectId: projectId,
|
||||
key: key,
|
||||
sizeByte: req.size,
|
||||
contentType: req.contentType,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
|
||||
return c.json({
|
||||
id: assetInfo.id,
|
||||
uploadUrl: uploadUrl,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import authnRoute from './authn'
|
||||
import { teamService } from '@/services/team/team'
|
||||
|
||||
describe('authn api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSignupInfo: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetSignupInfo = vi.spyOn(teamService, 'getSignupInfo')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /signup-info', async () => {
|
||||
mockGetSignupInfo.mockResolvedValue({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', authnRoute)
|
||||
const res = await app.request('/signup-info')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { z } from 'zod'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@/db'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const identifySchema = z.object({
|
||||
username: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/signup-info', async (c) => {
|
||||
const info = await teamService.getSignupInfo()
|
||||
return c.json({
|
||||
userCount: info.userCount,
|
||||
enablePublicSignup: info.enablePublicSignup,
|
||||
})
|
||||
})
|
||||
.get('/me', async (c) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
return c.json({ id: session?.user?.id ?? null })
|
||||
})
|
||||
.post('/identify', zValidator('json', identifySchema), async (c) => {
|
||||
const { username, email } = c.req.valid('json')
|
||||
|
||||
const dummyEmail = `guest_${ulid()}@guest.local`
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: username,
|
||||
email: dummyEmail,
|
||||
guestEmail: email,
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
return c.json({ id: user.id })
|
||||
})
|
||||
.all('/auth/*', (c) => {
|
||||
return auth.handler(c.req.raw)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,307 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('file api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-file')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/files/:fileId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/files', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'test-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
creator: { id: 'user1', name: 'user-name' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
isAi: false,
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'comment_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
commentMessage: 'hello',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.listComments).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'comment-id',
|
||||
assetId: 'test-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
creator: { id: 'user1', name: 'user-name' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
isAi: false,
|
||||
},
|
||||
],
|
||||
pageInfo: { cursor: 'cursor', total: 1 },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files', async () => {
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
const formData = new FormData()
|
||||
const file = new File(['test content'], 'test.jpg', { type: 'image/jpeg' })
|
||||
formData.append('file', file)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.key).toMatch(/^files\//)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
teamId: 'test-team',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import {
|
||||
updateFileRequestSchema,
|
||||
updateAssetOrderRequestSchema,
|
||||
deleteFilesRequestSchema,
|
||||
restoreFilesRequestSchema,
|
||||
createCommentRequestSchema,
|
||||
uploadFileRequestSchema,
|
||||
} from '@/dtos/asset'
|
||||
import { updateAssetMetadataRequestSchema } from '@/dtos/metadata'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { ulid } from 'ulid'
|
||||
import { z } from 'zod'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(fileId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put('/teams/:teamId/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: fileId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.delete('/teams/:teamId/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
|
||||
const hasStatus = req.some((m) => m.key === 'status')
|
||||
if (hasStatus) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json('')
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: fileId,
|
||||
userId: user.id,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/comments/:commentId', async (c) => {
|
||||
const commentId = c.req.param('commentId')
|
||||
const user = c.get('user')
|
||||
|
||||
const comment = await assetService.getComment(commentId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: comment.assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
return c.json(comment)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/files/restore',
|
||||
zValidator('json', restoreFilesRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { file } = c.req.valid('form')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return c.json('file too large, max 10MB', 400)
|
||||
}
|
||||
|
||||
const key = `files/${ulid()}`
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', key, buffer, file.size, file.type)
|
||||
|
||||
return c.json({ key })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import folderRoute from './folder'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { searchService } from '@/services/search/search'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('folder api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/folders/:folderId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders', async () => {
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({
|
||||
id: 'new-id',
|
||||
name: 'new-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'parent-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/folders/:folderId/children', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'child-id',
|
||||
name: 'child-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/children?assetType=folder')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('child-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/folders', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/folders/:folderId/search', async () => {
|
||||
vi.mocked(searchService.search).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'result-id',
|
||||
name: 'result-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
conditions: [{ field: 'name', operator: 'eq', value: 'result-folder' }],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('result-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Read',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/teams/test-team/folders/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
assetId: 'test-id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { searchService } from '@/services/search/search'
|
||||
import {
|
||||
createFolderRequestSchema,
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
} from '@/dtos/folder'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@/dtos/asset'
|
||||
import { searchRequestSchema } from '@/dtos/search'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const newAsset = await assetService.createAsset({
|
||||
name: req.name,
|
||||
parentId: req.parentId,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
return c.json(newAsset)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/folders/:folderId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(folderId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/teams/:teamId/folders/:folderId',
|
||||
zValidator('json', updateFolderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/folders/:folderId', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const assetInfo = await assetService.getAsset({ assetId: folderId })
|
||||
return c.json(assetInfo)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/folders/:folderId/children',
|
||||
zValidator('query', listChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/folders/restore',
|
||||
zValidator('json', restoreFoldersRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
assetId: id,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/folders/:folderId/search',
|
||||
zValidator('json', searchRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
assetId: folderId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import inviteRoute from './invite'
|
||||
import publicInviteRoute from './public-invite'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/invite/invite', () => ({
|
||||
inviteService: {
|
||||
createTeamInvite: vi.fn(),
|
||||
createProjectInvite: vi.fn(),
|
||||
getInvite: vi.fn(),
|
||||
consumeInvite: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'u1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
const getApp = () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicInviteRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', inviteRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('Invite API', () => {
|
||||
it('GET /invite/:code', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'My Team' },
|
||||
inviter: { name: 'Inviter' },
|
||||
role: 'editor',
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/invite/code123')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'code123',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'My Team',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/teams/t1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'editor' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
role: 'editor',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/invite', async () => {
|
||||
const app = getApp()
|
||||
const { authzService } = await import('@/services/authz/authz')
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined as never)
|
||||
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
project: { id: 'p1', name: 'Project A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
|
||||
const res = await app.request('/projects/p1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'reviewer' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
projectId: 'p1',
|
||||
projectName: 'Project A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
role: 'reviewer',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /join (Team)', async () => {
|
||||
const app = getApp()
|
||||
const { inviteService } = await import('@/services/invite/invite')
|
||||
const { notificationService } = await import('@/services/notification/notification')
|
||||
|
||||
vi.mocked(notificationService.create).mockResolvedValue(undefined as never)
|
||||
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as never)
|
||||
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as never)
|
||||
|
||||
const res = await app.request('/join', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ code: 'code123' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(inviteService.consumeInvite).toHaveBeenCalledWith('code123', 'u1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
createProjectInviteRequestSchema,
|
||||
createTeamInviteRequestSchema,
|
||||
joinRequestSchema,
|
||||
InviteInfo,
|
||||
} from '@/dtos/invite'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { inviteService } from '@/services/invite/invite'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/invite', zValidator('json', createTeamInviteRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
teamId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
})
|
||||
.post(
|
||||
'/projects/:projectId/invite',
|
||||
zValidator('json', createProjectInviteRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createProjectInvite({
|
||||
projectId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
},
|
||||
)
|
||||
.post('/join', zValidator('json', joinRequestSchema), async (c) => {
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
try {
|
||||
const info = await inviteService.getInvite(req.code)
|
||||
|
||||
await inviteService.consumeInvite(req.code, user.id)
|
||||
|
||||
if (info.projectId) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_project,
|
||||
teamId: info.teamId,
|
||||
projectId: info.projectId,
|
||||
userId: user.id,
|
||||
})
|
||||
} else {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: info.teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
} catch {
|
||||
return c.json({ error: 'Bad Request' }, 400)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import metadataRoute from './metadata'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { Prisma } from '@/generated/prisma/client.ts'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('metadata api', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Test Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'listTeamFields').mockResolvedValue([mockField])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
expect(json[0].aiAutofill).toBe(true)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'newfield',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'createTeamField').mockResolvedValue(mockField)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('newfield')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'PROJECT',
|
||||
config: { name: 'Project Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
} as Prisma.MetadataFieldGetPayload<Record<string, never>>
|
||||
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([
|
||||
{ field: mockField, visible: true },
|
||||
])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].visible).toBe(true)
|
||||
})
|
||||
|
||||
it('PATCH /projects/:projectId/fields/order', async () => {
|
||||
vi.spyOn(metadataService, 'updateProjectFieldsOrder').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/projects/p1/fields/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ fieldId: 'field1', visible: true }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
|
||||
{ fieldId: 'field1', visible: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/fields/:fieldId', async () => {
|
||||
vi.spyOn(metadataService, 'deleteTeamField').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/fields/f1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/files/:fileId/metadata', async () => {
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', metadataRoute)
|
||||
const res = await app.request('/teams/t1/files/f1/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'resolution_width', value: 1920 }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith('f1', [
|
||||
{ key: 'resolution_width', value: 1920 },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { z } from 'zod'
|
||||
import { Hono } from 'hono'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
createFieldRequestSchema,
|
||||
updateFieldRequestSchema,
|
||||
updateProjectFieldsOrderRequestSchema,
|
||||
updateAssetMetadataRequestSchema,
|
||||
FieldInfo,
|
||||
} from '@/dtos/metadata'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toFieldInfo(
|
||||
f: Prisma.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.createTeamField(teamId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/teams/:teamId/fields', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listTeamFields(teamId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f)))
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateTeamField(teamId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/fields/:fieldId', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.deleteTeamField(teamId, fieldId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.createProjectField(projectId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/projects/:projectId/fields', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listProjectFields(user.id, projectId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f.field, f.visible)))
|
||||
})
|
||||
.patch(
|
||||
'/projects/:projectId/fields/order',
|
||||
zValidator('json', updateProjectFieldsOrderRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
.put(
|
||||
'/projects/:projectId/fields/:fieldId',
|
||||
zValidator('json', updateFieldRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const field = await metadataService.updateProjectField(projectId, fieldId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
},
|
||||
)
|
||||
.delete('/projects/:projectId/fields/:fieldId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await metadataService.deleteProjectField(projectId, fieldId)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
|
||||
.patch(
|
||||
'/teams/:teamId/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const fileId = c.req.param('fileId') // Actually maps to assetId
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: fileId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { prisma } from '@/db'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export const authMiddleware = createMiddleware<{
|
||||
Variables: {
|
||||
user: User
|
||||
}
|
||||
}>(async (c, next) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('notification api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockList: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockMarkRead: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockList = vi.fn()
|
||||
mockMarkRead = vi.fn()
|
||||
vi.spyOn(notificationService, 'list').mockImplementation(mockList)
|
||||
vi.spyOn(notificationService, 'markRead').mockImplementation(mockMarkRead)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications', async () => {
|
||||
mockList.mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }],
|
||||
pageInfo: { total: 1, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(1)
|
||||
expect(json.pageInfo.cursor).toBe('abc')
|
||||
|
||||
expect(mockList).toHaveBeenCalledWith('t1', 'user1', {
|
||||
unreadOnly: true,
|
||||
after: undefined,
|
||||
pageSize: 10,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/read', async () => {
|
||||
mockMarkRead.mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', notificationRoute)
|
||||
const res = await app.request('/teams/t1/notifications/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notificationId: 'n1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockMarkRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
} from '@/dtos/notification'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get(
|
||||
'/teams/:teamId/notifications',
|
||||
zValidator('query', listNotificationsRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await notificationService.list(teamId, user.id, {
|
||||
unreadOnly: req.unreadOnly,
|
||||
after: req.after,
|
||||
pageSize: req.pageSize,
|
||||
})
|
||||
|
||||
// To align with Go struct casing, map pageInfo to page_info
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/notifications/read',
|
||||
zValidator('json', markNotificationReadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
await notificationService.markRead(teamId, user.id, req.notificationId)
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,178 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import projectRoute from './project'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('project api', () => {
|
||||
let mockListProjects: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProject: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetProjectTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListProjectMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockReparentAssets: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockListProjects = vi.fn()
|
||||
mockCreateProject = vi.fn()
|
||||
mockUpdateProject = vi.fn()
|
||||
mockGetProject = vi.fn()
|
||||
mockGetProjectTeam = vi.fn()
|
||||
mockListProjectMembers = vi.fn()
|
||||
mockReparentAssets = vi.fn()
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(projectService, 'listProjects').mockImplementation(mockListProjects)
|
||||
vi.spyOn(projectService, 'createProject').mockImplementation(mockCreateProject)
|
||||
vi.spyOn(projectService, 'updateProject').mockImplementation(mockUpdateProject)
|
||||
vi.spyOn(projectService, 'getProject').mockImplementation(mockGetProject)
|
||||
vi.spyOn(projectService, 'getProjectTeam').mockImplementation(mockGetProjectTeam)
|
||||
vi.spyOn(projectService, 'listProjectMembers').mockImplementation(mockListProjectMembers)
|
||||
vi.spyOn(assetService, 'reparentAssets').mockImplementation(mockReparentAssets)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects', async () => {
|
||||
mockListProjects.mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }],
|
||||
pageInfo: { total: 100, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects?page_size=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(100)
|
||||
expect(json.data[0].id).toBe('foo')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/projects', async () => {
|
||||
mockCreateProject.mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'foo.png',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('foo')
|
||||
expect(json.name).toBe('foo.png')
|
||||
expect(json.coverImage).toBe('http://s3/bucket/key')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/projects/:projectId', async () => {
|
||||
mockUpdateProject.mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'updated',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/teams/t/projects/foo', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'updated' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('updated')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId', async () => {
|
||||
mockGetProject.mockResolvedValue({
|
||||
id: 'p',
|
||||
name: 'foo.png',
|
||||
rootFolder: 'root_folder_id',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.rootFolder).toBe('root_folder_id')
|
||||
expect(json.id).toBe('p')
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/team', async () => {
|
||||
mockGetProjectTeam.mockResolvedValue('teamId')
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/team')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.teamId).toBe('teamId')
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/reparent', async () => {
|
||||
mockReparentAssets.mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', projectRoute)
|
||||
const res = await app.request('/projects/p/reparent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(1, {
|
||||
assetId: 'new_parent_id',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(2, {
|
||||
assetId: 'asset_1',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenNthCalledWith(3, {
|
||||
assetId: 'asset_2',
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: 'Edit',
|
||||
})
|
||||
expect(mockReparentAssets).toHaveBeenCalledWith({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
creatorId: 'user1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { reparentAssetsRequestSchema } from '@/dtos/asset'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
listProjectsRequestSchema,
|
||||
recentlyDeletedRequestSchema,
|
||||
} from '@/dtos/project'
|
||||
import { listMembersQuerySchema } from '@/dtos/team'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/projects', zValidator('json', createProjectRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const newProject = await projectService.createProject(user, {
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(newProject)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/projects/:projectId',
|
||||
zValidator('json', updateProjectRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(updatedProject)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/recently-deleted',
|
||||
zValidator('query', recentlyDeletedRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
// STUB: AssetService is not migrated yet.
|
||||
return c.json({ data: [], pageInfo: {} })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
sortBy: req.sortBy,
|
||||
sortDirection: req.sortDirection,
|
||||
pagination: req,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.get('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const p = await projectService.getProject(projectId)
|
||||
return c.json(p)
|
||||
})
|
||||
.get('/projects/:projectId/team', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
return c.json({ teamId })
|
||||
})
|
||||
.get('/projects/:projectId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/projects/:projectId/bots', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
return c.json([])
|
||||
})
|
||||
|
||||
.post(
|
||||
'/projects/:projectId/reparent',
|
||||
zValidator('json', reparentAssetsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Check Edit permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.reparentAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import providerRoute from './provider'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('provider api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', providerRoute)
|
||||
|
||||
let mockListByTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdate: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockDelete: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockListByTeam = vi.spyOn(providerService, 'listByTeam')
|
||||
mockCreate = vi.spyOn(providerService, 'create')
|
||||
mockUpdate = vi.spyOn(providerService, 'update')
|
||||
mockDelete = vi.spyOn(providerService, 'delete')
|
||||
|
||||
// Default to admin permission granted
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers returns providers', async () => {
|
||||
mockListByTeam.mockResolvedValue([{ id: 'p1', name: 'openai', config: {} }])
|
||||
|
||||
const res = await app.request('/teams/t1/providers')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
permission: 'Admin',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers/:id/models returns models', async () => {
|
||||
const mockListModelsByProvider = vi.spyOn(providerService, 'listModelsByProvider')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockListModelsByProvider.mockResolvedValue([{ modelId: 'm1', name: 'model1' } as any])
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1/models')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].modelId).toBe('m1')
|
||||
expect(mockListModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers creates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
|
||||
const res = await app.request('/teams/t1/providers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'openai', config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('openai')
|
||||
expect(mockCreate).toHaveBeenCalledWith('t1', 'openai', config, models)
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/providers/:id updates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://new-url.com',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
mockUpdate.mockResolvedValue({ id: 'p1', name: 'openai', config, models })
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.config.baseUrl).toBe('https://new-url.com')
|
||||
expect(mockUpdate).toHaveBeenCalledWith('t1', 'p1', config, models)
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/providers/:id deletes provider', async () => {
|
||||
mockDelete.mockResolvedValue({ id: 'p1' })
|
||||
|
||||
const res = await app.request('/teams/t1/providers/p1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(mockDelete).toHaveBeenCalledWith('t1', 'p1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { providerService } from '@/services/provider/provider'
|
||||
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/providers', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const providers = await providerService.listByTeam(teamId)
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.get('/teams/:teamId/providers/:id/models', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const models = await providerService.listModelsByProvider(teamId, id)
|
||||
return c.json(models)
|
||||
})
|
||||
|
||||
.post('/teams/:teamId/providers', zValidator('json', createProviderRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { name, config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const provider = await providerService.create(teamId, name, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.put(
|
||||
'/teams/:teamId/providers/:id',
|
||||
zValidator('json', updateProviderRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const provider = await providerService.update(teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
},
|
||||
)
|
||||
|
||||
.delete('/teams/:teamId/providers/:id', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await providerService.delete(teamId, id)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono'
|
||||
import { inviteService } from '@/services/invite/invite'
|
||||
import { InviteInfo } from '@/dtos/invite'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = app.get('/invite/:code', async (c) => {
|
||||
const code = c.req.param('code')
|
||||
try {
|
||||
const inv = await inviteService.getInvite(code)
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
} catch {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,250 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@/services/metadata/metadata'
|
||||
import { FieldInfo } from '@/dtos/metadata'
|
||||
import type { Prisma as PrismaType } from '@/generated/prisma/client'
|
||||
import { auth } from '@/services/auth/auth'
|
||||
import { prisma } from '@/db'
|
||||
import { createCommentRequestSchema } from '@/dtos/asset'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
function toFieldInfo(
|
||||
f: PrismaType.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/shares/:shareId/info', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json({
|
||||
id: shareLink.id,
|
||||
name: shareLink.name,
|
||||
expireAt: shareLink.expireAt,
|
||||
isDisabled: shareLink.isDisabled,
|
||||
isExpired: shareLink.isExpired,
|
||||
hasPassword: shareLink.hasPassword,
|
||||
rootFolderId: shareLink.rootFolderId,
|
||||
projectId: shareLink.projectId,
|
||||
})
|
||||
} catch (err) {
|
||||
return c.json({ error: (err as Error).message }, 404)
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/fields', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
|
||||
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
|
||||
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
|
||||
|
||||
return c.json(
|
||||
fields
|
||||
.filter((f) => fieldVisibility[f.field.key])
|
||||
.map((f) => toFieldInfo(f.field, f.visible)),
|
||||
)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/folders/:folderId/children',
|
||||
zValidator('query', sharedChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(folderId, password)
|
||||
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
|
||||
if (shareLink.defaultSortOrder) {
|
||||
const parts = shareLink.defaultSortOrder.split(':')
|
||||
sort = parts[0]
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const res = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const res = await assetService.listComments(targetFileId, req)
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const guestUserId = c.req.header('x-guest-user-id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: shareLink.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
|
||||
if (!project) {
|
||||
throw new Error('Project not found')
|
||||
}
|
||||
|
||||
// Identify user
|
||||
let userId: string | null = null
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else if (guestUserId) {
|
||||
const guestUser = await prisma.user.findUnique({
|
||||
where: { id: guestUserId },
|
||||
})
|
||||
if (guestUser) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: targetFileId,
|
||||
userId: userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: project.teamId,
|
||||
creatorId: userId,
|
||||
assetId: targetFileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import route from './s3'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
describe('S3 API', () => {
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key sets Content-Type', async () => {
|
||||
const mockHead = vi.spyOn(s3Service, 'headObject').mockResolvedValue({
|
||||
key: 'test.webp',
|
||||
size: 100,
|
||||
lastModified: new Date(),
|
||||
contentType: 'image/webp',
|
||||
eTag: '"test"',
|
||||
})
|
||||
const mockGet = vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'image/webp' })
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('image/webp')
|
||||
expect(mockHead).toHaveBeenCalledWith('b1', 'test.webp')
|
||||
expect(mockGet).toHaveBeenCalledWith('b1', 'test.webp')
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key handles missing contentType', async () => {
|
||||
vi.spyOn(s3Service, 'headObject').mockResolvedValue({
|
||||
key: 'test',
|
||||
size: 100,
|
||||
lastModified: new Date(),
|
||||
contentType: 'application/octet-stream',
|
||||
eTag: '"test"',
|
||||
})
|
||||
vi.spyOn(s3Service, 'getObject').mockResolvedValue({ buffer: Buffer.from('test'), contentType: 'application/octet-stream' })
|
||||
|
||||
const res = await app.request('/files/b1/test')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
|
||||
})
|
||||
|
||||
it('GET /files/:bucket/:key returns 404 if not found', async () => {
|
||||
vi.spyOn(s3Service, 'headObject').mockRejectedValue(new Error('NoSuchKey'))
|
||||
|
||||
const res = await app.request('/files/b1/not-found')
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Hono } from 'hono'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
|
||||
const route = new Hono()
|
||||
.get('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
|
||||
try {
|
||||
const info = await s3Service.headObject(bucket, key)
|
||||
const { buffer: data, contentType } = await s3Service.getObject(bucket, key)
|
||||
|
||||
if (contentType) {
|
||||
c.header('Content-Type', contentType)
|
||||
} else if (info.contentType) {
|
||||
c.header('Content-Type', info.contentType)
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return c.body(data as any)
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
if (error.message?.includes('NoSuchKey')) {
|
||||
return c.text('Not Found', 404)
|
||||
}
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
.put('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
const body = await c.req.arrayBuffer()
|
||||
|
||||
try {
|
||||
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
|
||||
return c.text('OK')
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import shareRoute from './share'
|
||||
import publicShareRoute from './public-share'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Share API', () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicShareRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', shareRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
describe('GET /shares/:shareId/info', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'Public Share',
|
||||
isDisabled: false,
|
||||
isExpired: false,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/info', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.name).toBe('Public Share')
|
||||
expect(body.hasPassword).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/folders/:folderId/children', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'My Share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
password: null,
|
||||
expireAt: null,
|
||||
defaultSortOrder: 'name:asc',
|
||||
fieldVisibility: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'folder1',
|
||||
assetType: 'file',
|
||||
sort: 'name',
|
||||
order: 'asc',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// Protected Routes
|
||||
describe('POST /teams/:teamId/projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'My Share' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.id).toBe('share1')
|
||||
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/projects/project1/shares', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/shares/:shareId', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/shares/:shareId/assets', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
|
||||
|
||||
const res = await app.request('/teams/team1/shares/share1/assets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.addedCount).toBe(1)
|
||||
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { shareService } from '@/services/share/share'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
updateShareLinkRequestSchema,
|
||||
listShareLinksRequestSchema,
|
||||
addAssetToShareRequestSchema,
|
||||
} from '@/dtos/share'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
zValidator('json', createShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, req)
|
||||
return c.json(shareLink)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/teams/:teamId/projects/:projectId/shares',
|
||||
zValidator('query', listShareLinksRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const res = await shareService.listProjectShareLinks({
|
||||
...req,
|
||||
projectId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/shares/:shareId',
|
||||
zValidator('json', updateShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await shareService.deleteShareLink(shareId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/shares/:shareId/assets',
|
||||
zValidator('json', addAssetToShareRequestSchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Also check if user has read permission on the source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
}
|
||||
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const assetId = c.req.param('assetId') // symlink asset id
|
||||
const user = c.get('user')
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await authzService.hasPermission({
|
||||
projectId: shareLink.projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await shareService.removeAssetFromShare(shareId, assetId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import skillRoute from './skill'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { authzService } from '@/services/authz/authz'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'read',
|
||||
Edit: 'edit',
|
||||
Admin: 'admin',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Skill API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', skillRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/skills', () => {
|
||||
test('Success', async () => {
|
||||
const mockSkills = [
|
||||
{
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
vi.spyOn(skillService, 'listSkills').mockResolvedValue(mockSkills)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ skills: mockSkills })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ permission: 'admin' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/skills', () => {
|
||||
test('Success with assetId', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
|
||||
})
|
||||
|
||||
test('Success with githubUrl', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ githubUrl: 'https://github.com/test/repo' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
|
||||
githubUrl: 'https://github.com/test/repo',
|
||||
})
|
||||
})
|
||||
|
||||
test('Forbidden without Admin permission', async () => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockRejectedValueOnce(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500) // The app uses a global error handler that returns 500 for thrown errors in these tests
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /teams/:teamId/skills/:id', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /teams/:teamId/skills/:id/config', () => {
|
||||
test('Success', async () => {
|
||||
const mockConfig = {
|
||||
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
|
||||
}
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: mockConfig,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills/skill1/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ config: mockConfig }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { skillService } from '@/services/skill/skill'
|
||||
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@/dtos/skill'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/skills', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(teamId)
|
||||
return c.json({ skills })
|
||||
})
|
||||
.post('/teams/:teamId/skills', zValidator('json', upsertSkillRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
try {
|
||||
const skill = await skillService.upsertSkill(teamId, req)
|
||||
return c.json(skill)
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === 'ConflictError') {
|
||||
return c.json({ error: err.message }, 409)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
.delete('/teams/:teamId/skills/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/skills/:id/config',
|
||||
zValidator('json', updateSkillConfigRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,187 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import teamRoute from './team'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { userMetadataService } from '@/services/user-metadata/user-metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
|
||||
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
|
||||
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
|
||||
mockGetMe = vi.spyOn(teamService, 'getMe')
|
||||
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
|
||||
mockGetSettings = vi.spyOn(teamService, 'getSettings')
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /teams creates a new team', async () => {
|
||||
const mockTeam = { id: 't1', name: 'New Team', updatedAt: new Date() }
|
||||
mockCreateTeam.mockResolvedValue(mockTeam)
|
||||
|
||||
const res = await app.request('/teams', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Team',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.id).toBe('t1')
|
||||
expect(mockCreateTeam).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user1' }),
|
||||
expect.objectContaining({ name: 'New Team' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams returns user teams', async () => {
|
||||
mockGetUserTeams.mockResolvedValue({
|
||||
data: [{ id: 't1', name: 'User Team', updatedAt: new Date() }],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams?first=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.data[0].id).toBe('t1')
|
||||
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/members joins team and sends notification', async () => {
|
||||
mockJoinTeam.mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/t1/members', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
|
||||
expect(mockCreateNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'new_user_join_team',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/me returns user role in team', async () => {
|
||||
mockGetMe.mockResolvedValue({ id: 'user1', name: 'Test User', role: 'owner' })
|
||||
|
||||
const res = await app.request('/teams/t1/me')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.role).toBe('owner')
|
||||
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/members returns members', async () => {
|
||||
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
|
||||
|
||||
const res = await app.request('/teams/t1/members')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings returns settings', async () => {
|
||||
mockGetSettings.mockResolvedValue({ someKey: 'some_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('some_value')
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates settings', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ someKey: 'new_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'someKey', value: 'new_value' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('new_value')
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
{ key: 'key2', value: 'value2' },
|
||||
])
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(2)
|
||||
expect(data[0].key).toBe('key1')
|
||||
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/user-metadata/:key upserts the metadata', async () => {
|
||||
mockUpsertUserMetadata.mockResolvedValue({ key: 'key1', value: 'value1' })
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata/key1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ value: 'value1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.key).toBe('key1')
|
||||
expect(data.value).toBe('value1')
|
||||
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
|
||||
})
|
||||
})
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { teamService } from '@/services/team/team'
|
||||
import { userMetadataService } from '@/services/user-metadata/user-metadata'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
import {
|
||||
createTeamRequestSchema,
|
||||
getUserTeamsRequestSchema,
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
} from '@/dtos/team'
|
||||
import { updateUserMetadataRequestSchema } from '@/dtos/user-metadata'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams', zValidator('json', createTeamRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const newTeam = await teamService.createTeam(user, req)
|
||||
return c.json(newTeam)
|
||||
})
|
||||
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const pg = c.req.valid('query')
|
||||
|
||||
const teams = await teamService.getUserTeams({
|
||||
userId: user.id,
|
||||
pagination: pg,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: teams.data,
|
||||
pageInfo: {
|
||||
total: teams.pageInfo.total,
|
||||
cursor: teams.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.post('/teams/:teamId/members', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await teamService.joinTeam({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/me', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const me = await teamService.getMe({
|
||||
teamId,
|
||||
user,
|
||||
})
|
||||
|
||||
return c.json(me)
|
||||
})
|
||||
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/teams/:teamId/settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/settings',
|
||||
zValidator('json', updateTeamSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
})
|
||||
|
||||
const settings = await teamService.updateSettings(teamId, req.key, req.value)
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/user-metadata', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.listMetadata(user.id, teamId)
|
||||
return c.json(metadata)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/user-metadata/:key',
|
||||
zValidator('json', updateUserMetadataRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const key = c.req.param('key')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
|
||||
return c.json({ key: metadata.key, value: metadata.value })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import uploadRoute from './upload'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { uploadService } from '@/services/upload/upload'
|
||||
import type { CreateUploadTaskResponse, TaskInfo } from '@/dtos/upload'
|
||||
import type { PaginatedData } from '@/services/pagination'
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// We use any here because mocking Hono context and middleware
|
||||
// with full type safety is overly complex for these unit tests.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/services/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Upload API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: {},
|
||||
} as unknown as PaginatedData<TaskInfo[]>)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.listUploadTasks).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
|
||||
taskId: 'task1',
|
||||
presignedUrls: [],
|
||||
} as unknown as CreateUploadTaskResponse)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
parentId: 'parent1',
|
||||
files: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.createUploadTask).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
|
||||
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks/task1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileId: 'file1',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
|
||||
fileId: 'file1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { uploadService } from '@/services/upload/upload'
|
||||
import {
|
||||
confirmFileUploadRequestSchema,
|
||||
createUploadTaskRequestSchema,
|
||||
localUploadQuerySchema,
|
||||
} from '@/dtos/upload'
|
||||
import { paginationParamsSchema } from '@/dtos/pagination'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { notificationService } from '@/services/notification/notification'
|
||||
import { NotificationType } from '@/generated/prisma/client'
|
||||
import { s3Service, verifyLocalUrlSignature } from '@/services/s3/s3'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => {
|
||||
const { bucket, key, Signature } = c.req.valid('query')
|
||||
|
||||
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
|
||||
return c.text('Invalid signature', 403)
|
||||
}
|
||||
|
||||
const contentType = c.req.header('Content-Type')
|
||||
let buffer: Buffer
|
||||
let size: number
|
||||
let finalContentType = contentType
|
||||
|
||||
if (contentType?.includes('multipart/form-data')) {
|
||||
const body = await c.req.parseBody()
|
||||
const file = body['file'] as File
|
||||
if (!file) {
|
||||
return c.text('No file uploaded', 400)
|
||||
}
|
||||
buffer = Buffer.from(await file.arrayBuffer())
|
||||
size = file.size
|
||||
finalContentType = file.type || 'application/octet-stream'
|
||||
} else {
|
||||
const arrayBuffer = await c.req.arrayBuffer()
|
||||
buffer = Buffer.from(arrayBuffer)
|
||||
size = arrayBuffer.byteLength
|
||||
}
|
||||
|
||||
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const params = c.req.valid('query')
|
||||
|
||||
const tasks = await uploadService.listUploadTasks(user.id, params)
|
||||
return c.json(tasks)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/upload/tasks',
|
||||
zValidator('json', createUploadTaskRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
teamId,
|
||||
assetId: req.parentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const resp = await uploadService.createUploadTask(user.id, req)
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.patch(
|
||||
'/teams/:teamId/upload/tasks/:taskId',
|
||||
zValidator('json', confirmFileUploadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const taskId = c.req.param('taskId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: teamId,
|
||||
creatorId: user.id,
|
||||
assetId: req.fileId,
|
||||
taskId: taskId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import versionStackRoute from './versionStack'
|
||||
import { authMiddleware } from '@/api/middleware/auth'
|
||||
import { versionStackService } from '@/services/versionStack/versionStack'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
|
||||
vi.mock('@/services/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn(),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/api/middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks', () => {
|
||||
it('should create a version stack and return asset info', async () => {
|
||||
const mockStack = { id: 'stack1' }
|
||||
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
|
||||
|
||||
mockCreateVersionStack.mockResolvedValue(mockStack)
|
||||
mockGetAsset.mockResolvedValue(mockAssetInfo)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileIds: ['f1', 'f2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockAssetInfo)
|
||||
|
||||
expect(mockCreateVersionStack).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
creatorId: 'user1',
|
||||
fileIds: ['f1', 'f2'],
|
||||
})
|
||||
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ wrongField: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockCreateVersionStack).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks/:stackID/order', () => {
|
||||
it('should change order and return 200', async () => {
|
||||
mockChangeStackFileVersion.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'f1',
|
||||
beforeId: 'f2',
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail with validation error for invalid body', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1' }), // missing beforeId
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(mockChangeStackFileVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { versionStackService } from '@/services/versionStack/versionStack'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import {
|
||||
createVersionStackRequestSchema,
|
||||
changeStackFileVersionRequestSchema,
|
||||
} from '@/dtos/versionStack'
|
||||
import type { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const route = app
|
||||
.post(
|
||||
'/projects/:projectID/version_stacks',
|
||||
zValidator('json', createVersionStackRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectID')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
const stack = await versionStackService.createVersionStack({
|
||||
fileIds: req.fileIds,
|
||||
projectId,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const stackInfo = await assetService.getAsset({ assetId: stack.id })
|
||||
|
||||
return c.json(stackInfo)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/projects/:projectID/version_stacks/:stackID/order',
|
||||
zValidator('json', changeStackFileVersionRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectID')
|
||||
const stackId = c.req.param('stackID')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
projectId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
await versionStackService.changeStackFileVersion({
|
||||
stackId,
|
||||
fileId: req.fileId,
|
||||
beforeId: req.beforeId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
Reference in New Issue
Block a user