Add shared file storage with folder tree, permissions, and file manager UI

New document hub for centralized file storage — replaces scattered
drives and USB sticks for non-technical SMBs. Three new tables:
storage_folder (nested hierarchy), storage_folder_permission (role
and user-level access control), storage_file.

Backend: folder CRUD with nested paths, file upload/download via
signed URLs, permission checks (view/edit/admin with inheritance
from parent folders), public/private toggle, breadcrumb navigation,
file search.

Frontend: two-panel file manager — collapsible folder tree on left,
icon grid view on right. Folder icons by type, file size display,
upload button, context menu for download/delete. Breadcrumb nav.
Files sidebar link added.
This commit is contained in:
Ryan Moon
2026-03-29 15:31:20 -05:00
parent d36c6f7135
commit 0f6cc104d2
13 changed files with 1093 additions and 1 deletions

View File

@@ -0,0 +1,32 @@
CREATE TYPE "storage_folder_access" AS ENUM ('view', 'edit', 'admin');
CREATE TABLE "storage_folder" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"parent_id" uuid,
"name" varchar(255) NOT NULL,
"path" text NOT NULL DEFAULT '/',
"created_by" uuid REFERENCES "user"("id"),
"is_public" boolean NOT NULL DEFAULT true,
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE TABLE "storage_folder_permission" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"folder_id" uuid NOT NULL REFERENCES "storage_folder"("id") ON DELETE CASCADE,
"role_id" uuid REFERENCES "role"("id"),
"user_id" uuid REFERENCES "user"("id"),
"access_level" "storage_folder_access" NOT NULL DEFAULT 'view',
"created_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE TABLE "storage_file" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"folder_id" uuid NOT NULL REFERENCES "storage_folder"("id") ON DELETE CASCADE,
"filename" varchar(255) NOT NULL,
"path" varchar(1000) NOT NULL,
"content_type" varchar(100) NOT NULL,
"size_bytes" integer NOT NULL,
"uploaded_by" uuid REFERENCES "user"("id"),
"created_at" timestamp with time zone NOT NULL DEFAULT now()
);

View File

@@ -155,6 +155,13 @@
"when": 1774810000000,
"tag": "0021_remove_company_scoping",
"breakpoints": true
},
{
"idx": 22,
"version": "7",
"when": 1774820000000,
"tag": "0022_shared_file_storage",
"breakpoints": true
}
]
}

View File

@@ -0,0 +1,55 @@
import {
pgTable,
uuid,
varchar,
text,
timestamp,
boolean,
integer,
pgEnum,
} from 'drizzle-orm/pg-core'
import { users } from './users.js'
import { roles } from './rbac.js'
export const storageFolderAccessEnum = pgEnum('storage_folder_access', ['view', 'edit', 'admin'])
export const storageFolders = pgTable('storage_folder', {
id: uuid('id').primaryKey().defaultRandom(),
parentId: uuid('parent_id'),
name: varchar('name', { length: 255 }).notNull(),
path: text('path').notNull().default('/'),
createdBy: uuid('created_by').references(() => users.id),
isPublic: boolean('is_public').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
})
export const storageFolderPermissions = pgTable('storage_folder_permission', {
id: uuid('id').primaryKey().defaultRandom(),
folderId: uuid('folder_id')
.notNull()
.references(() => storageFolders.id, { onDelete: 'cascade' }),
roleId: uuid('role_id').references(() => roles.id),
userId: uuid('user_id').references(() => users.id),
accessLevel: storageFolderAccessEnum('access_level').notNull().default('view'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
})
export const storageFiles = pgTable('storage_file', {
id: uuid('id').primaryKey().defaultRandom(),
folderId: uuid('folder_id')
.notNull()
.references(() => storageFolders.id, { onDelete: 'cascade' }),
filename: varchar('filename', { length: 255 }).notNull(),
path: varchar('path', { length: 1000 }).notNull(),
contentType: varchar('content_type', { length: 100 }).notNull(),
sizeBytes: integer('size_bytes').notNull(),
uploadedBy: uuid('uploaded_by').references(() => users.id),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
})
export type StorageFolder = typeof storageFolders.$inferSelect
export type StorageFolderInsert = typeof storageFolders.$inferInsert
export type StorageFolderPermission = typeof storageFolderPermissions.$inferSelect
export type StorageFile = typeof storageFiles.$inferSelect
export type StorageFileInsert = typeof storageFiles.$inferInsert

View File

@@ -16,6 +16,7 @@ import { lookupRoutes } from './routes/v1/lookups.js'
import { fileRoutes } from './routes/v1/files.js'
import { rbacRoutes } from './routes/v1/rbac.js'
import { repairRoutes } from './routes/v1/repairs.js'
import { storageRoutes } from './routes/v1/storage.js'
import { RbacService } from './services/rbac.service.js'
export async function buildApp() {
@@ -67,6 +68,7 @@ export async function buildApp() {
await app.register(fileRoutes, { prefix: '/v1' })
await app.register(rbacRoutes, { prefix: '/v1' })
await app.register(repairRoutes, { prefix: '/v1' })
await app.register(storageRoutes, { prefix: '/v1' })
// Auto-seed system permissions on startup
app.addHook('onReady', async () => {

View File

@@ -0,0 +1,185 @@
import type { FastifyPluginAsync } from 'fastify'
import multipart from '@fastify/multipart'
import { PaginationSchema } from '@forte/shared/schemas'
import { StorageFolderService, StorageFileService, StoragePermissionService } from '../../services/storage.service.js'
import { ValidationError } from '../../lib/errors.js'
export const storageRoutes: FastifyPluginAsync = async (app) => {
await app.register(multipart, {
limits: { fileSize: 50 * 1024 * 1024, files: 1 },
})
// --- Folders ---
app.post('/storage/folders', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
const { name, parentId, isPublic } = request.body as { name?: string; parentId?: string; isPublic?: boolean }
if (!name?.trim()) throw new ValidationError('Folder name is required')
// Check parent access if creating subfolder
if (parentId) {
const accessLevel = await StoragePermissionService.getAccessLevel(app.db, parentId, request.user.id)
if (!accessLevel || accessLevel === 'view') {
return reply.status(403).send({ error: { message: 'No edit access to parent folder', statusCode: 403 } })
}
}
const folder = await StorageFolderService.create(app.db, { name: name.trim(), parentId, isPublic, createdBy: request.user.id })
return reply.status(201).send(folder)
})
app.get('/storage/folders', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { parentId } = request.query as { parentId?: string }
const folders = parentId
? await StorageFolderService.listChildren(app.db, parentId)
: await StorageFolderService.listChildren(app.db, null)
return reply.send({ data: folders })
})
app.get('/storage/folders/tree', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const folders = await StorageFolderService.listAllAccessible(app.db, request.user.id)
return reply.send({ data: folders })
})
app.get('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const folder = await StorageFolderService.getById(app.db, id)
if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })
const hasAccess = await StoragePermissionService.canAccess(app.db, id, request.user.id)
if (!hasAccess) return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })
const breadcrumbs = await StorageFolderService.getBreadcrumbs(app.db, id)
return reply.send({ ...folder, breadcrumbs })
})
app.patch('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const { name, isPublic } = request.body as { name?: string; isPublic?: boolean }
const accessLevel = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
if (!accessLevel || accessLevel === 'view') {
return reply.status(403).send({ error: { message: 'No edit access', statusCode: 403 } })
}
const folder = await StorageFolderService.update(app.db, id, { name, isPublic })
if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })
return reply.send(folder)
})
app.delete('/storage/folders/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const accessLevel = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
if (accessLevel !== 'admin') {
return reply.status(403).send({ error: { message: 'Admin access required', statusCode: 403 } })
}
const folder = await StorageFolderService.delete(app.db, id)
if (!folder) return reply.status(404).send({ error: { message: 'Folder not found', statusCode: 404 } })
return reply.send(folder)
})
// --- Folder Permissions ---
app.get('/storage/folders/:id/permissions', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const permissions = await StoragePermissionService.listPermissions(app.db, id)
return reply.send({ data: permissions })
})
app.post('/storage/folders/:id/permissions', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const { roleId, userId, accessLevel } = request.body as { roleId?: string; userId?: string; accessLevel?: string }
const myAccess = await StoragePermissionService.getAccessLevel(app.db, id, request.user.id)
if (myAccess !== 'admin') {
return reply.status(403).send({ error: { message: 'Admin access required to manage permissions', statusCode: 403 } })
}
if (!roleId && !userId) throw new ValidationError('Either roleId or userId is required')
if (!accessLevel || !['view', 'edit', 'admin'].includes(accessLevel)) throw new ValidationError('accessLevel must be view, edit, or admin')
const perm = await StoragePermissionService.setPermission(app.db, id, roleId, userId, accessLevel)
return reply.status(201).send(perm)
})
app.delete('/storage/folder-permissions/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const perm = await StoragePermissionService.removePermission(app.db, id)
if (!perm) return reply.status(404).send({ error: { message: 'Permission not found', statusCode: 404 } })
return reply.send(perm)
})
// --- Files ---
app.post('/storage/folders/:folderId/files', { preHandler: [app.authenticate, app.requirePermission('files.upload')] }, async (request, reply) => {
const { folderId } = request.params as { folderId: string }
const accessLevel = await StoragePermissionService.getAccessLevel(app.db, folderId, request.user.id)
if (!accessLevel || accessLevel === 'view') {
return reply.status(403).send({ error: { message: 'No edit access to this folder', statusCode: 403 } })
}
const data = await request.file()
if (!data) throw new ValidationError('No file provided')
const buffer = await data.toBuffer()
const file = await StorageFileService.upload(app.db, app.storage, {
folderId,
data: buffer,
filename: data.filename,
contentType: data.mimetype,
uploadedBy: request.user.id,
})
return reply.status(201).send(file)
})
app.get('/storage/folders/:folderId/files', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { folderId } = request.params as { folderId: string }
const hasAccess = await StoragePermissionService.canAccess(app.db, folderId, request.user.id)
if (!hasAccess) return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })
const params = PaginationSchema.parse(request.query)
const result = await StorageFileService.listByFolder(app.db, folderId, params)
return reply.send(result)
})
app.delete('/storage/files/:id', { preHandler: [app.authenticate, app.requirePermission('files.delete')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const file = await StorageFileService.getById(app.db, id)
if (!file) return reply.status(404).send({ error: { message: 'File not found', statusCode: 404 } })
const accessLevel = await StoragePermissionService.getAccessLevel(app.db, file.folderId, request.user.id)
if (!accessLevel || accessLevel === 'view') {
return reply.status(403).send({ error: { message: 'No edit access', statusCode: 403 } })
}
const deleted = await StorageFileService.delete(app.db, app.storage, id)
return reply.send(deleted)
})
app.get('/storage/files/:id/signed-url', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { id } = request.params as { id: string }
const file = await StorageFileService.getById(app.db, id)
if (!file) return reply.status(404).send({ error: { message: 'File not found', statusCode: 404 } })
const hasAccess = await StoragePermissionService.canAccess(app.db, file.folderId, request.user.id)
if (!hasAccess) return reply.status(403).send({ error: { message: 'Access denied', statusCode: 403 } })
const token = app.jwt.sign({ path: file.path, purpose: 'file-access' } as any, { expiresIn: '15m' })
const signedUrl = `/v1/files/s/${file.path}?token=${token}`
return reply.send({ url: signedUrl })
})
app.get('/storage/files/search', { preHandler: [app.authenticate, app.requirePermission('files.view')] }, async (request, reply) => {
const { q } = request.query as { q?: string }
if (!q) return reply.send({ data: [], pagination: { page: 1, limit: 25, total: 0, totalPages: 0 } })
const params = PaginationSchema.parse(request.query)
const result = await StorageFileService.search(app.db, q, params)
return reply.send(result)
})
}

View File

@@ -0,0 +1,277 @@
import { eq, and, count, ilike, inArray, or, isNull, type Column } from 'drizzle-orm'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import { storageFolders, storageFolderPermissions, storageFiles } from '../db/schema/storage.js'
import { userRoles } from '../db/schema/rbac.js'
import type { StorageProvider } from '../storage/index.js'
import { randomUUID } from 'crypto'
import { withPagination, withSort, buildSearchCondition, paginatedResponse } from '../utils/pagination.js'
import type { PaginationInput } from '@forte/shared/schemas'
function getExtension(contentType: string): string {
const map: Record<string, string> = {
'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp',
'application/pdf': 'pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
'application/msword': 'doc', 'application/vnd.ms-excel': 'xls',
'text/plain': 'txt', 'text/csv': 'csv',
}
return map[contentType] ?? contentType.split('/')[1] ?? 'bin'
}
// --- Permission Service ---
export const StoragePermissionService = {
async canAccess(db: PostgresJsDatabase<any>, folderId: string, userId: string): Promise<boolean> {
// Check if folder is public
const [folder] = await db.select({ isPublic: storageFolders.isPublic }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (!folder) return false
if (folder.isPublic) return true
// Check direct user permission
const [userPerm] = await db.select({ id: storageFolderPermissions.id }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
.limit(1)
if (userPerm) return true
// Check role-based permission
const userRoleIds = await db.select({ roleId: userRoles.roleId }).from(userRoles).where(eq(userRoles.userId, userId))
if (userRoleIds.length > 0) {
const roleIds = userRoleIds.map((r) => r.roleId)
const [rolePerm] = await db.select({ id: storageFolderPermissions.id }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), inArray(storageFolderPermissions.roleId, roleIds)))
.limit(1)
if (rolePerm) return true
}
// Check parent folder (inherited permissions)
const [parentFolder] = await db.select({ parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (parentFolder?.parentId) {
return this.canAccess(db, parentFolder.parentId, userId)
}
return false
},
async getAccessLevel(db: PostgresJsDatabase<any>, folderId: string, userId: string): Promise<'admin' | 'edit' | 'view' | null> {
const [folder] = await db.select({ isPublic: storageFolders.isPublic, createdBy: storageFolders.createdBy }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (!folder) return null
// Creator always has admin
if (folder.createdBy === userId) return 'admin'
// Check direct user permission
const [userPerm] = await db.select({ accessLevel: storageFolderPermissions.accessLevel }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
.limit(1)
if (userPerm) return userPerm.accessLevel
// Check role-based permission
const userRoleIds = await db.select({ roleId: userRoles.roleId }).from(userRoles).where(eq(userRoles.userId, userId))
if (userRoleIds.length > 0) {
const roleIds = userRoleIds.map((r) => r.roleId)
const [rolePerm] = await db.select({ accessLevel: storageFolderPermissions.accessLevel }).from(storageFolderPermissions)
.where(and(eq(storageFolderPermissions.folderId, folderId), inArray(storageFolderPermissions.roleId, roleIds)))
.limit(1)
if (rolePerm) return rolePerm.accessLevel
}
// Check parent (inherited)
const [parentFolder] = await db.select({ parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, folderId)).limit(1)
if (parentFolder?.parentId) {
return this.getAccessLevel(db, parentFolder.parentId, userId)
}
// Public folders give view access
if (folder.isPublic) return 'view'
return null
},
async listPermissions(db: PostgresJsDatabase<any>, folderId: string) {
return db.select().from(storageFolderPermissions).where(eq(storageFolderPermissions.folderId, folderId))
},
async setPermission(db: PostgresJsDatabase<any>, folderId: string, roleId: string | undefined, userId: string | undefined, accessLevel: string) {
// Remove existing permission for this role/user on this folder
if (roleId) {
await db.delete(storageFolderPermissions).where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.roleId, roleId)))
}
if (userId) {
await db.delete(storageFolderPermissions).where(and(eq(storageFolderPermissions.folderId, folderId), eq(storageFolderPermissions.userId, userId)))
}
const [perm] = await db.insert(storageFolderPermissions).values({
folderId,
roleId: roleId ?? null,
userId: userId ?? null,
accessLevel: accessLevel as any,
}).returning()
return perm
},
async removePermission(db: PostgresJsDatabase<any>, permissionId: string) {
const [perm] = await db.delete(storageFolderPermissions).where(eq(storageFolderPermissions.id, permissionId)).returning()
return perm ?? null
},
}
// --- Folder Service ---
export const StorageFolderService = {
async create(db: PostgresJsDatabase<any>, input: { name: string; parentId?: string; isPublic?: boolean; createdBy?: string }) {
// Build materialized path
let path = '/'
if (input.parentId) {
const [parent] = await db.select({ path: storageFolders.path, name: storageFolders.name }).from(storageFolders).where(eq(storageFolders.id, input.parentId)).limit(1)
if (parent) path = `${parent.path}${parent.name}/`
}
const [folder] = await db.insert(storageFolders).values({
name: input.name,
parentId: input.parentId ?? null,
path,
isPublic: input.isPublic ?? true,
createdBy: input.createdBy ?? null,
}).returning()
return folder
},
async getById(db: PostgresJsDatabase<any>, id: string) {
const [folder] = await db.select().from(storageFolders).where(eq(storageFolders.id, id)).limit(1)
return folder ?? null
},
async listChildren(db: PostgresJsDatabase<any>, parentId: string | null) {
const where = parentId ? eq(storageFolders.parentId, parentId) : isNull(storageFolders.parentId)
return db.select().from(storageFolders).where(where).orderBy(storageFolders.name)
},
async listAllAccessible(db: PostgresJsDatabase<any>, userId: string) {
// Get all folders and filter by access — for the tree view
const allFolders = await db.select().from(storageFolders).orderBy(storageFolders.name)
// For each folder, check access (this is simplified — in production you'd optimize with a single query)
const accessible = []
for (const folder of allFolders) {
if (folder.isPublic || folder.createdBy === userId) {
accessible.push(folder)
continue
}
const hasAccess = await StoragePermissionService.canAccess(db, folder.id, userId)
if (hasAccess) accessible.push(folder)
}
return accessible
},
async update(db: PostgresJsDatabase<any>, id: string, input: { name?: string; isPublic?: boolean }) {
const [folder] = await db.update(storageFolders).set({ ...input, updatedAt: new Date() }).where(eq(storageFolders.id, id)).returning()
return folder ?? null
},
async delete(db: PostgresJsDatabase<any>, id: string) {
// CASCADE handles permissions and files via FK
const [folder] = await db.delete(storageFolders).where(eq(storageFolders.id, id)).returning()
return folder ?? null
},
async getBreadcrumbs(db: PostgresJsDatabase<any>, folderId: string): Promise<{ id: string; name: string }[]> {
const crumbs: { id: string; name: string }[] = []
let currentId: string | null = folderId
while (currentId) {
const [folder] = await db.select({ id: storageFolders.id, name: storageFolders.name, parentId: storageFolders.parentId }).from(storageFolders).where(eq(storageFolders.id, currentId)).limit(1)
if (!folder) break
crumbs.unshift({ id: folder.id, name: folder.name })
currentId = folder.parentId
}
return crumbs
},
}
// --- File Service ---
export const StorageFileService = {
async upload(db: PostgresJsDatabase<any>, storage: StorageProvider, input: {
folderId: string
data: Buffer
filename: string
contentType: string
uploadedBy?: string
}) {
const fileId = randomUUID()
const ext = getExtension(input.contentType)
const storagePath = `storage/${input.folderId}/${fileId}.${ext}`
await storage.put(storagePath, input.data, input.contentType)
const [file] = await db.insert(storageFiles).values({
id: fileId,
folderId: input.folderId,
filename: input.filename,
path: storagePath,
contentType: input.contentType,
sizeBytes: input.data.length,
uploadedBy: input.uploadedBy ?? null,
}).returning()
return file
},
async listByFolder(db: PostgresJsDatabase<any>, folderId: string, params: PaginationInput) {
const baseWhere = eq(storageFiles.folderId, folderId)
const searchCondition = params.q
? buildSearchCondition(params.q, [storageFiles.filename])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
const sortableColumns: Record<string, Column> = {
filename: storageFiles.filename,
size_bytes: storageFiles.sizeBytes,
created_at: storageFiles.createdAt,
}
let query = db.select().from(storageFiles).where(where).$dynamic()
query = withSort(query, params.sort, params.order, sortableColumns, storageFiles.filename)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(storageFiles).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async getById(db: PostgresJsDatabase<any>, id: string) {
const [file] = await db.select().from(storageFiles).where(eq(storageFiles.id, id)).limit(1)
return file ?? null
},
async delete(db: PostgresJsDatabase<any>, storage: StorageProvider, id: string) {
const file = await this.getById(db, id)
if (!file) return null
await storage.delete(file.path)
const [deleted] = await db.delete(storageFiles).where(eq(storageFiles.id, id)).returning()
return deleted ?? null
},
async search(db: PostgresJsDatabase<any>, query: string, params: PaginationInput) {
const searchCondition = buildSearchCondition(query, [storageFiles.filename])
if (!searchCondition) return paginatedResponse([], 0, params.page, params.limit)
const sortableColumns: Record<string, Column> = {
filename: storageFiles.filename,
created_at: storageFiles.createdAt,
}
let q = db.select().from(storageFiles).where(searchCondition).$dynamic()
q = withSort(q, params.sort, params.order, sortableColumns, storageFiles.filename)
q = withPagination(q, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
q,
db.select({ total: count() }).from(storageFiles).where(searchCondition),
])
return paginatedResponse(data, total, params.page, params.limit)
},
}