initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+226
View File
@@ -0,0 +1,226 @@
import { describe, expect, it, beforeEach, vi } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { SearchService } from './search'
import { AssetType, Prisma } from '@/generated/prisma/client.ts'
describe('N-gram Search Integration', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
it('should automatically populate nameNgram on asset creation', async () => {
const asset = await prisma.asset.create({
data: {
name: 'Apple Pie',
type: AssetType.file,
status: 'uploaded',
sizeByte: 100,
},
})
expect(asset.nameNgram).toContain('app')
expect(asset.nameNgram).toContain('pie')
expect(asset.nameNgram).toContain('ple')
})
it('should automatically update nameNgram on asset update', async () => {
const asset = await prisma.asset.create({
data: {
name: 'Apple',
type: AssetType.file,
status: 'uploaded',
},
})
const updated = await prisma.asset.update({
where: { id: asset.id },
data: { name: 'Banana' },
})
expect(updated.nameNgram).toContain('ban')
expect(updated.nameNgram).not.toContain('app')
})
it('should find assets using n-gram search', async () => {
const root = await prisma.asset.create({
data: { name: 'root', type: AssetType.folder, status: 'uploaded' },
})
await prisma.asset.create({
data: { name: '北京大学', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
await prisma.asset.create({
data: { name: '清华大学', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
conditions: [
{
field: 'name',
operator: 'contains',
value: '北京',
},
],
})
expect(result.data).toHaveLength(1)
expect(result.data[0].name).toBe('北京大学')
})
it('should handle false positives correctly using the recheck', async () => {
const root = await prisma.asset.create({
data: { name: 'root', type: AssetType.folder, status: 'uploaded' },
})
await prisma.asset.create({
data: { name: 'hello world', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
await prisma.asset.create({
data: { name: 'hellXello', type: AssetType.file, status: 'uploaded', parentId: root.id },
})
const result = await searchService.search(root.id, {
operator: 'AND',
recursively: true,
conditions: [
{
field: 'name',
operator: 'contains',
value: 'hello',
},
],
})
expect(result.data).toHaveLength(1)
expect(result.data[0].name).toBe('hello world')
})
describe('N-gram Search Matrix', () => {
let rootId: string
beforeEach(async () => {
const root = await prisma.asset.create({
data: { name: 'matrix-root', type: AssetType.folder, status: 'uploaded' },
})
rootId = root.id
const names = [
'apple.png',
'banana_v2.mp4',
'北京大学-最终版.docx',
'清华大学-final.pdf',
'project-2026-05-10',
'123456789.txt',
'hellXello',
'hello world',
'my-awesome-asset',
'我的资源',
'foo-bar',
'foo bar',
]
for (const name of names) {
await prisma.asset.create({
data: {
name,
type: AssetType.file,
status: 'uploaded',
parentId: rootId,
},
})
}
})
it.each([
{ val: 'apple', expected: ['apple.png'] },
{ val: 'v2', expected: ['banana_v2.mp4'] },
{ val: '北京', expected: ['北京大学-最终版.docx'] },
{ val: '大学', expected: ['北京大学-最终版.docx', '清华大学-final.pdf'] },
{ val: 'final', expected: ['清华大学-final.pdf'] },
{ val: '2026', expected: ['project-2026-05-10'] },
{ val: 'hello', expected: ['hello world'] },
{ val: 'awesome', expected: ['my-awesome-asset'] },
{ val: '资源', expected: ['我的资源'] },
{ val: '123', expected: ['123456789.txt'] },
{ val: 'docx', expected: ['北京大学-最终版.docx'] },
{ val: 'none-match', expected: [] },
// Hyphen/Space sensitivity tests
{ val: 'foo-bar', expected: ['foo-bar'] },
{ val: 'foo bar', expected: ['foo bar'] },
])('should match "$val" with names $expected', async ({ val, expected }) => {
const result = await searchService.search(rootId, {
operator: 'AND',
recursively: true,
conditions: [
{
field: 'name',
operator: 'contains',
value: val,
},
],
})
const actualNames = result.data.map((a) => a.name).sort()
expect(actualNames).toEqual(expected.sort())
})
})
describe('Switching Search Probe Logic', () => {
let rootId: string
beforeEach(async () => {
const root = await prisma.asset.create({
data: { name: 'probe-root', type: AssetType.folder, status: 'uploaded' },
})
rootId = root.id
})
it('should use GIN index when probe count is less than 10001', async () => {
// Mock count to return a rare count
const countSpy = vi.spyOn(prisma.asset, 'count').mockResolvedValue(5)
const findManySpy = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([])
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
conditions: [{ field: 'name', operator: 'contains', value: 'rareterm' }],
})
// Check that findMany was called with nameNgram condition
const findManyArgs = findManySpy.mock.calls[0][0] as Prisma.AssetFindManyArgs
const where = findManyArgs.where as Prisma.AssetWhereInput
expect(where).toHaveProperty('nameNgram')
expect(where.nameNgram).toHaveProperty('hasEvery')
countSpy.mockRestore()
findManySpy.mockRestore()
})
it('should fallback to simple ILIKE when probe count is 10001 or more', async () => {
// Mock count to return a common count for the probe, and again for the full count
const countSpy = vi.spyOn(prisma.asset, 'count').mockResolvedValue(10001)
const findManySpy = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([])
await searchService.search(rootId, {
operator: 'AND',
recursively: true,
conditions: [{ field: 'name', operator: 'contains', value: 'commonterm' }],
})
// Check that findMany was called WITHOUT nameNgram condition, and WITH name contains
const findManyArgs = findManySpy.mock.calls[0][0] as Prisma.AssetFindManyArgs
const where = findManyArgs.where as Prisma.AssetWhereInput
expect(where).not.toHaveProperty('nameNgram')
expect(where).toHaveProperty('name')
expect(where.name).toHaveProperty('contains', 'commonterm')
countSpy.mockRestore()
findManySpy.mockRestore()
})
})
})
+531
View File
@@ -0,0 +1,531 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { SearchService } from './search'
import { SearchConditionOperator } from '@/dtos/search'
import { metadataService } from '@/services/metadata/metadata'
import { AssetType } from '@/generated/prisma/client.ts'
describe('SearchService', () => {
setupTestDbHooks()
let searchService: SearchService
beforeEach(() => {
searchService = new SearchService()
})
const setupBasicAssets = async () => {
const user = await prisma.user.create({
data: { name: 'test-user-search', email: 'search-user@example.com', type: 'human' },
})
const team = await prisma.team.create({
data: { name: 'test-team' },
})
const project = await prisma.project.create({
data: { name: 'test-project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
sizeByte: 0,
status: 'uploaded',
},
})
const subFolder = await prisma.asset.create({
data: {
name: 'subfolder',
type: AssetType.folder,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 0,
status: 'uploaded',
},
})
const file1 = await prisma.asset.create({
data: {
name: 'file1',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: user.id,
sizeByte: 100,
status: 'uploaded',
createdAt: new Date('2023-01-01T00:00:00Z'),
},
})
const file2 = await prisma.asset.create({
data: {
name: 'file2',
type: AssetType.file,
projectId: project.id,
parentId: subFolder.id,
creatorId: user.id,
sizeByte: 200,
status: 'uploaded',
createdAt: new Date('2023-01-01T00:00:01Z'),
},
})
await prisma.assetMetadataValue.create({
data: {
assetId: file2.id,
fieldId: 'status',
stringValue: 'approved',
},
})
return { rootFolder, subFolder, file1, file2 }
}
const setupMatrixAssets = async () => {
const user = await prisma.user.create({
data: { name: 'matrix-user', email: 'matrix@example.com', type: 'human' },
})
const team = await prisma.team.create({ data: { name: 'matrix-team' } })
const project = await prisma.project.create({ data: { name: 'matrix-proj', teamId: team.id } })
const root = await prisma.asset.create({
data: {
name: 'matrix-root',
type: AssetType.folder,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
},
})
const createWithMeta = async (name: string, meta: Record<string, unknown>) => {
const asset = await prisma.asset.create({
data: {
name,
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 100,
},
})
const reqs = Object.entries(meta).map(([key, value]) => ({ key, value }))
await metadataService.updateAssetMetadata(asset.id, reqs)
return asset
}
// String fields
await createWithMeta('str-apple', { text: 'apple' })
await createWithMeta('str-banana', { text: 'banana' })
// Number fields
await createWithMeta('num-10', { num: 10 })
await createWithMeta('num-20', { num: 20 })
// Bool fields
await createWithMeta('bool-true', { bool: true })
await createWithMeta('bool-false', { bool: false })
// SelectMulti
await createWithMeta('multi-a-b', { multi: ['a', 'b'] })
await createWithMeta('multi-b-c', { multi: ['b', 'c'] })
// Date
await createWithMeta('date-today', { date: new Date().toISOString() })
const yesterday = new Date()
yesterday.setDate(yesterday.getDate() - 1)
await createWithMeta('date-yesterday', { date: yesterday.toISOString() })
// Name field specific tests
await createWithMeta('name-contains-test', {})
// One with nothing
await prisma.asset.create({
data: {
name: 'nothing',
type: AssetType.file,
projectId: project.id,
parentId: root.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 100,
},
})
return { root }
}
describe('Exhaustive Operator Matrix', () => {
let rootId: string
beforeEach(async () => {
const { root } = await setupMatrixAssets()
rootId = root.id
})
it.each([
// Name field (System)
{ field: 'name', op: 'eq', val: 'str-apple', expected: ['str-apple'] },
{
field: 'name',
op: 'neq',
val: 'str-apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'contains', val: 'apple', expected: ['str-apple'] },
{
field: 'name',
op: 'notContains',
val: 'apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'isEmpty', val: '', expected: [] }, // name is never empty in this setup
{
field: 'name',
op: 'isNotEmpty',
val: '',
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
// String Metadata
{ field: 'text', op: 'eq', val: 'apple', expected: ['str-apple'] },
{
field: 'text',
op: 'neq',
val: 'apple',
expected: [
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{
field: 'text',
op: 'isEmpty',
val: null,
expected: [
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'text', op: 'isNotEmpty', val: null, expected: ['str-apple', 'str-banana'] },
// Number Metadata
{ field: 'num', op: 'eq', val: 10, expected: ['num-10'] },
{
field: 'num',
op: 'neq',
val: 10,
expected: [
'str-apple',
'str-banana',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'num', op: 'gt', val: 15, expected: ['num-20'] },
{ field: 'num', op: 'lt', val: 15, expected: ['num-10'] },
{ field: 'num', op: 'gte', val: 20, expected: ['num-20'] },
{ field: 'num', op: 'lte', val: 10, expected: ['num-10'] },
// Boolean Metadata
{ field: 'bool', op: 'eq', val: true, expected: ['bool-true'] },
{ field: 'bool', op: 'eq', val: false, expected: ['bool-false'] },
// SelectMulti Metadata
{ field: 'multi', op: 'hasAny', val: ['a'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAny', val: ['b'], expected: ['multi-a-b', 'multi-b-c'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'b'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'c'], expected: [] },
{
field: 'multi',
op: 'hasNone',
val: ['a'],
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'multi', op: 'eq', val: ['a', 'b'], expected: ['multi-a-b'] },
// Date Metadata
{ field: 'date', op: 'eq', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'isWithin', val: 'today', expected: ['date-today'] },
{ field: 'date', op: 'lt', val: 'today', expected: ['date-yesterday'] },
{ field: 'date', op: 'gt', val: 'yesterday', expected: ['date-today'] },
// System Fields (native columns)
{
field: 'sizeByte',
op: 'gt',
val: 50,
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'name', op: 'contains', val: 'apple', expected: ['str-apple'] },
{
field: 'createdAt',
op: 'gt',
val: 'one week ago',
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'multi-a-b',
'multi-b-c',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
])('filters $field with $op $val', async ({ field, op, val, expected }) => {
const result = await searchService.search(rootId, {
conditions: [{ field, operator: op as SearchConditionOperator, value: val }],
recursively: true,
assetType: 'file',
operator: 'AND',
})
const names = result.data.map((a) => a.name).sort()
expect(names).toEqual(expected.sort())
})
})
it('searches for assets by name (equals)', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'eq', value: 'file1' }],
recursively: true,
assetType: 'file',
operator: 'AND',
})
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file1.id)
})
it('searches for assets by name (contains)', async () => {
const { rootFolder, file1, file2 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'contains', value: 'file' }],
recursively: true,
assetType: 'file',
operator: 'AND',
})
expect(result.data).toHaveLength(2)
const ids = result.data.map((a) => a.id)
expect(ids).toContain(file1.id)
expect(ids).toContain(file2.id)
})
it('searches for assets by metadata (equals)', async () => {
const { rootFolder, file2 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
recursively: true,
assetType: 'file',
operator: 'AND',
})
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file2.id)
})
it('searches only in the specified folder if recursively is false', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
const result = await searchService.search(rootFolder.id, {
conditions: [{ field: 'name', operator: 'contains', value: 'file' }],
recursively: false,
assetType: 'file',
operator: 'AND',
})
// Should only find file1, as file2 is in subfolder
expect(result.data).toHaveLength(1)
expect(result.data[0].id).toBe(file1.id)
})
it('sorts by createdAt', async () => {
const { rootFolder } = await setupBasicAssets()
// file1 was created before file2, but file2 is in subfolder.
// wait, I need to be sure about the creation order.
// setupBasicAssets creates file1 then file2.
const resultAsc = await searchService.search(rootFolder.id, {
sort: { field: 'createdAt', order: 'asc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
})
expect(resultAsc.data[0].name).toBe('file1')
expect(resultAsc.data[1].name).toBe('file2')
const resultDesc = await searchService.search(rootFolder.id, {
sort: { field: 'createdAt', order: 'desc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
})
expect(resultDesc.data[0].name).toBe('file2')
expect(resultDesc.data[1].name).toBe('file1')
})
it('sorts by sizeByte', async () => {
const { rootFolder } = await setupBasicAssets()
// file1 size 100, file2 size 200
const resultAsc = await searchService.search(rootFolder.id, {
sort: { field: 'sizeByte', order: 'asc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
})
expect(resultAsc.data[0].sizeByte).toBe(100)
expect(resultAsc.data[1].sizeByte).toBe(200)
const resultDesc = await searchService.search(rootFolder.id, {
sort: { field: 'sizeByte', order: 'desc' },
recursively: true,
assetType: 'file',
operator: 'AND',
conditions: [],
})
expect(resultDesc.data[0].sizeByte).toBe(200)
expect(resultDesc.data[1].sizeByte).toBe(100)
})
it('includes symlinks when showSymlink is true', async () => {
const { rootFolder, file1 } = await setupBasicAssets()
// Create a symlink in the root folder pointing to file2
const symlink = await prisma.asset.create({
data: {
name: 'symlink-to-file2',
type: AssetType.symlink,
projectId: file1.projectId,
parentId: rootFolder.id,
targetId: file1.id, // Pointing to file1 for simplicity
status: 'uploaded',
},
})
// Search without showSymlink
const resultNormal = await searchService.search(rootFolder.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
})
expect(resultNormal.data.find((a) => a.id === symlink.id)).toBeUndefined()
// Search with showSymlink
const resultWithSymlink = await searchService.search(rootFolder.id, {
recursively: false,
assetType: 'file',
operator: 'AND',
conditions: [],
showSymlink: true,
})
expect(resultWithSymlink.data.find((a) => a.id === symlink.id)).toBeDefined()
})
})
+573
View File
@@ -0,0 +1,573 @@
import { prisma } from '@/db'
import { Prisma, AssetType } from '@/generated/prisma/client.ts'
import { AssetService, assetService } from '@/services/asset/asset'
import { AssetInfo } from '@/dtos/asset'
import { SearchRequest } from '@/dtos/search'
import { paginateQuery, PaginatedData } from '@/services/pagination'
import { generateSearchNgrams } from '@/utils/ngram'
export class SearchService {
constructor(
private readonly prismaClient: typeof prisma = prisma,
private readonly assetSvc: AssetService = assetService,
) {}
async search(folderId: string, req: SearchRequest): Promise<PaginatedData<AssetInfo[]>> {
let targetFolderIds: string[] = []
if (req.recursively === false) {
targetFolderIds = [folderId]
} else {
targetFolderIds = await this.assetSvc.getDescendantFolderIds(folderId)
}
const where: Prisma.AssetWhereInput = {
removed: false,
}
if (targetFolderIds.length > 0) {
where.parentId = { in: targetFolderIds }
}
const targetType = req.assetType === 'folder' ? AssetType.folder : AssetType.file
const typeCondition: Prisma.AssetWhereInput = req.showSymlink
? {
OR: [
{ type: targetType },
{
type: AssetType.symlink,
target: { type: targetType },
},
],
}
: { type: targetType }
if (req.conditions && req.conditions.length > 0) {
const conditionPredicates: Prisma.AssetWhereInput[] = req.conditions.map((cond) => {
return this.buildConditionPredicate(cond.field, cond.operator as string, cond.value)
})
if (req.operator === 'OR') {
where.AND = [typeCondition, { OR: conditionPredicates }]
} else {
where.AND = [typeCondition, ...conditionPredicates]
}
} else {
Object.assign(where, typeCondition)
}
// AI Semantic search is skipped for now, but in the future we'll check if req.query exists
// and if the team has embeddings enabled to do a vector search
const orderBy: Prisma.AssetOrderByWithRelationInput = {}
if (req.sort) {
const direction = req.sort.order === 'desc' ? 'desc' : 'asc'
if (req.sort.field === 'custom') {
orderBy.sortIndex = 'asc'
} else if (req.sort.field === 'name') {
orderBy.name = direction
} else if (req.sort.field === 'created_at' || req.sort.field === 'createdAt') {
orderBy.createdAt = direction
} else if (req.sort.field === 'size_byte' || req.sort.field === 'sizeByte') {
orderBy.sizeByte = direction
} else {
orderBy.id = 'desc'
}
} else {
orderBy.sortIndex = 'asc'
}
// ----------------------------------------------------------------------
// Switching Search Implementation
// ----------------------------------------------------------------------
let finalWhere = where
let countOverride: number | undefined
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
if (nameCond) {
const valStr = String(nameCond.value)
const ngrams = generateSearchNgrams(valStr)
if (ngrams.length > 0) {
const PROBE_LIMIT = 10001
// We need to build the probe WHERE clause manually since it's a mix of existing conditions and n-grams
// For the probe, we use both GIN and ILIKE to ensure correctness
const probeWhere = {
...where,
nameNgram: { hasEvery: ngrams },
name: { contains: valStr, mode: 'insensitive' as const },
}
const probeCount = await this.prismaClient.asset.count({
where: probeWhere,
take: PROBE_LIMIT,
})
if (probeCount < PROBE_LIMIT) {
// SELECTIVE CASE: The term is rare. Use GIN index for high performance.
finalWhere = {
...where,
nameNgram: { hasEvery: ngrams },
name: { contains: valStr, mode: 'insensitive' },
}
countOverride = probeCount
} else {
// NON-SELECTIVE CASE: The term is common.
// Revert to simple ILIKE to allow B-tree short-circuiting during pagination.
// We set countOverride to PROBE_LIMIT to avoid a full table scan for the count.
finalWhere = {
...where,
name: { contains: valStr, mode: 'insensitive' },
}
countOverride = PROBE_LIMIT
}
} else {
// Fallback for queries that yield no n-grams
finalWhere = {
...where,
name: { contains: valStr, mode: 'insensitive' },
}
}
}
const { data: assets, pageInfo } = await paginateQuery(
(skip, take) =>
this.prismaClient.asset.findMany({
where: finalWhere,
orderBy,
skip,
take,
}),
countOverride !== undefined
? async () => countOverride!
: () => this.prismaClient.asset.count({ where: finalWhere }),
req,
)
const assetInfos = await this.assetSvc.listAssetsByIds(assets.map((a) => a.id))
return { data: assetInfos, pageInfo }
}
private buildConditionPredicate(
field: string,
operator: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
): Prisma.AssetWhereInput {
if (field === 'name') {
const valStr = String(value)
switch (operator) {
case 'eq':
return { name: { equals: valStr } }
case 'neq':
return { name: { not: valStr } }
case 'contains':
// We handle 'contains' specially in the main search loop for Switching Search.
// Here we just return the simple condition as a fallback.
return { name: { contains: valStr, mode: 'insensitive' } }
case 'notContains':
return { NOT: { name: { contains: valStr, mode: 'insensitive' } } }
case 'isEmpty':
return { name: { equals: '' } }
case 'isNotEmpty':
return { name: { not: '' } }
default:
throw new Error(`Unsupported operator for name field: ${operator}`)
}
}
if (field === 'sizeByte' || field === 'size_byte') {
const valNum = Number(value)
switch (operator) {
case 'eq':
return { sizeByte: { equals: valNum } }
case 'neq':
return { sizeByte: { not: valNum } }
case 'gt':
return { sizeByte: { gt: valNum } }
case 'gte':
return { sizeByte: { gte: valNum } }
case 'lt':
return { sizeByte: { lt: valNum } }
case 'lte':
return { sizeByte: { lte: valNum } }
default:
throw new Error(`Unsupported operator for sizeByte field: ${operator}`)
}
}
if (
field === 'createdAt' ||
field === 'updatedAt' ||
field === 'created_at' ||
field === 'updated_at'
) {
const col = field === 'createdAt' || field === 'created_at' ? 'createdAt' : 'updatedAt'
const valDate = this.toDate(value)
switch (operator) {
case 'eq':
return { [col]: { equals: valDate } }
case 'neq':
return { [col]: { not: valDate } }
case 'gt':
return { [col]: { gt: this.toDateBound(value, 'end') } }
case 'gte':
return { [col]: { gte: this.toDateBound(value, 'start') } }
case 'lt':
return { [col]: { lt: this.toDateBound(value, 'start') } }
case 'lte':
return { [col]: { lte: this.toDateBound(value, 'end') } }
case 'isWithin': {
const range = this.parseDateRange(value)
return {
[col]: {
gte: range.start,
lte: range.end,
},
}
}
default:
throw new Error(`Unsupported operator for ${field} field: ${operator}`)
}
}
// EAV queries on metadataValues
const baseFilter = { fieldId: field }
// Handle Empty/NotEmpty globally for EAV
if (operator === 'isEmpty') {
return { metadataValues: { none: { fieldId: field } } }
}
if (operator === 'isNotEmpty') {
return { metadataValues: { some: { fieldId: field } } }
}
const valuePredicate = (): Prisma.AssetMetadataValueWhereInput => {
const or: Prisma.AssetMetadataValueWhereInput[] = []
if (typeof value === 'string' && !this.isDate(value)) {
or.push({ stringValue: value })
}
if (typeof value === 'number') {
or.push({ numberValue: value })
}
if (typeof value === 'boolean') {
or.push({ booleanValue: value })
}
if (this.isDate(value)) {
const d = this.parseRelativeDate(value)
if (d instanceof Date) {
or.push({ dateValue: d })
} else if (d && 'gte' in d) {
return {
dateValue: {
gte: d.gte,
lte: d.lte,
},
}
}
}
if (
Array.isArray(value) ||
(typeof value === 'object' && value !== null && !(value instanceof Date))
) {
or.push({ jsonValue: { equals: value } })
}
if (or.length === 1) return or[0]
return { OR: or }
}
switch (operator) {
case 'eq':
return {
metadataValues: {
some: {
...baseFilter,
...valuePredicate(),
},
},
}
case 'neq':
return {
// "is not" in EAV context: either the field doesn't exist,
// OR it exists but has a different value.
OR: [
{ metadataValues: { none: { fieldId: field } } },
{
metadataValues: {
some: {
fieldId: field,
NOT: valuePredicate(),
},
},
},
],
}
case 'gt':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { gt: Number(value) } },
{ dateValue: { gt: this.toDateBound(value, 'end') } },
],
},
},
}
case 'gte':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { gte: Number(value) } },
{ dateValue: { gte: this.toDateBound(value, 'start') } },
],
},
},
}
case 'lt':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { lt: Number(value) } },
{ dateValue: { lt: this.toDateBound(value, 'start') } },
],
},
},
}
case 'lte':
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ numberValue: { lte: Number(value) } },
{ dateValue: { lte: this.toDateBound(value, 'end') } },
],
},
},
}
case 'contains':
return {
metadataValues: {
some: {
...baseFilter,
stringValue: { contains: String(value), mode: 'insensitive' },
},
},
}
case 'notContains':
return {
metadataValues: {
none: {
...baseFilter,
stringValue: { contains: String(value), mode: 'insensitive' },
},
},
}
case 'in': // "is any of"
return {
metadataValues: {
some: {
...baseFilter,
OR: [
{ stringValue: { in: Array.isArray(value) ? value : [value] } },
{
numberValue: { in: Array.isArray(value) ? (value as number[]) : [Number(value)] },
},
],
},
},
}
case 'notIn': // "is none of"
return {
metadataValues: {
none: {
...baseFilter,
OR: [
{ stringValue: { in: Array.isArray(value) ? value : [value] } },
{
numberValue: { in: Array.isArray(value) ? (value as number[]) : [Number(value)] },
},
],
},
},
}
case 'hasAny':
return {
metadataValues: {
some: {
...baseFilter,
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
},
}
case 'hasAll':
return {
metadataValues: {
some: {
...baseFilter,
AND: Array.isArray(value)
? value.map((v) => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: v },
}))
: [
{
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
],
},
},
}
case 'hasNone':
return {
metadataValues: {
none: {
...baseFilter,
// eslint-disable-next-line @typescript-eslint/naming-convention
jsonValue: { array_contains: value },
},
},
}
case 'isWithin': {
const range = this.parseDateRange(value)
return {
metadataValues: {
some: {
...baseFilter,
dateValue: {
gte: range.start,
lte: range.end,
},
},
},
}
}
default:
throw new Error(`Unsupported operator for metadata field: ${operator}`)
}
}
private isDate(value: unknown): boolean {
if (value instanceof Date) return true
if (typeof value !== 'string') return false
const valStr = value.toLowerCase()
const relativeKeywords = [
'today',
'yesterday',
'tomorrow',
'one week ago',
'one week from now',
'one month ago',
'one month from now',
]
if (relativeKeywords.includes(valStr) || valStr.match(/\d+\s+days?\s+(ago|from\s+now)/)) {
return true
}
const d = new Date(value)
return !isNaN(d.getTime()) && value.includes('-')
}
private toDate(value: unknown): Date {
return this.toDateBound(value, 'start')
}
private toDateBound(value: unknown, bound: 'start' | 'end'): Date {
const d = this.parseRelativeDate(value)
if (d instanceof Date) return d
if (d && 'gte' in d && 'lte' in d) {
return bound === 'start' ? d.gte! : d.lte!
}
return new Date(value as string)
}
private parseDateRange(value: unknown): { start: Date; end: Date } {
const d = this.parseRelativeDate(value)
if (d && 'gte' in d && 'lte' in d) {
return { start: d.gte!, end: d.lte! }
}
const date = d instanceof Date ? d : new Date(value as string)
const start = new Date(date)
start.setHours(0, 0, 0, 0)
const end = new Date(date)
end.setHours(23, 59, 59, 999)
return { start, end }
}
private parseRelativeDate(value: unknown): { gte?: Date; lte?: Date } | Date | null {
if (value instanceof Date) return value
const valStr = String(value).toLowerCase()
const now = new Date()
const startOf = (d: Date) => {
const res = new Date(d)
res.setHours(0, 0, 0, 0)
return res
}
const endOf = (d: Date) => {
const res = new Date(d)
res.setHours(23, 59, 59, 999)
return res
}
if (valStr === 'today') {
return { gte: startOf(now), lte: endOf(now) }
}
if (valStr === 'yesterday') {
const d = new Date(now)
d.setDate(d.getDate() - 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'tomorrow') {
const d = new Date(now)
d.setDate(d.getDate() + 1)
return { gte: startOf(d), lte: endOf(d) }
}
if (valStr === 'one week ago') {
const d = new Date(now)
d.setDate(d.getDate() - 7)
return d
}
if (valStr === 'one week from now') {
const d = new Date(now)
d.setDate(d.getDate() + 7)
return d
}
if (valStr === 'one month ago') {
const d = new Date(now)
d.setMonth(d.getMonth() - 1)
return d
}
if (valStr === 'one month from now') {
const d = new Date(now)
d.setMonth(d.getMonth() + 1)
return d
}
const daysAgoMatch = valStr.match(/(\d+)\s+days?\s+ago/)
if (daysAgoMatch) {
const d = new Date(now)
d.setDate(d.getDate() - parseInt(daysAgoMatch[1]))
return d
}
const daysFromNowMatch = valStr.match(/(\d+)\s+days?\s+from\s+now/)
if (daysFromNowMatch) {
const d = new Date(now)
d.setDate(d.getDate() + parseInt(daysFromNowMatch[1]))
return d
}
const parsed = new Date(value as string)
return isNaN(parsed.getTime()) ? null : parsed
}
}
export const searchService = new SearchService()