11// server/api/[model]/[id].patch.ts
22import { eventHandler , getRouterParams , readBody , createError } from 'h3'
33import { eq } from 'drizzle-orm'
4- import { getTableForModel , filterUpdatableFields , filterHiddenFields , filterPublicColumns } from '../../utils/modelMapper'
5-
4+ import { getTableForModel , filterUpdatableFields } from '../../utils/modelMapper'
65import type { TableWithId } from '../../types'
76// @ts -expect-error - #site/drizzle is an alias defined by the module
87import { useDrizzle } from '#site/drizzle'
9-
10- import { useAutoCrudConfig } from '../../utils/config'
11- import { checkAdminAccess } from '../../utils/auth'
8+ import { ensureResourceAccess , formatResourceResult } from '../../utils/handler'
129
1310export default eventHandler ( async ( event ) => {
14- const { resources } = useAutoCrudConfig ( )
1511 const { model, id } = getRouterParams ( event ) as { model : string , id : string }
16-
17- const isAdmin = await checkAdminAccess ( event , model , 'update' )
18-
19- // Check public access if not admin
20- if ( ! isAdmin ) {
21- const resourceConfig = resources ?. [ model ]
22- const isPublic = resourceConfig ?. public === true || ( Array . isArray ( resourceConfig ?. public ) && resourceConfig . public . includes ( 'update' ) )
23-
24- if ( ! isPublic ) {
25- throw createError ( {
26- statusCode : 401 ,
27- message : 'Unauthorized' ,
28- } )
29- }
30- }
12+ const isAdmin = await ensureResourceAccess ( event , model , 'update' )
3113
3214 const table = getTableForModel ( model ) as TableWithId
3315
@@ -36,7 +18,8 @@ export default eventHandler(async (event) => {
3618
3719 // Automatically update updatedAt if it exists
3820 if ( 'updatedAt' in table ) {
39- payload . updatedAt = new Date ( )
21+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
22+ ( payload as any ) . updatedAt = new Date ( )
4023 }
4124
4225 const updatedRecord = await useDrizzle ( )
@@ -53,10 +36,5 @@ export default eventHandler(async (event) => {
5336 } )
5437 }
5538
56- if ( isAdmin ) {
57- return filterHiddenFields ( model , updatedRecord as Record < string , unknown > )
58- }
59- else {
60- return filterPublicColumns ( model , updatedRecord as Record < string , unknown > )
61- }
39+ return formatResourceResult ( model , updatedRecord as Record < string , unknown > , isAdmin )
6240} )
0 commit comments