import { RequestHandler } from 'express' ; import Joi from 'joi' ; import { InvalidPayloadException } from '../exceptions' ; import { FailedValidationException } from '@directus/shared/exceptions' ; import asyncHandler from '../utils/async-handler' ; import { sanitizeQuery } from '../utils/sanitize-query' ; export const validateBatch = ( scope ) : RequestHandler => asyncHandler ( async ( req , res , next ) => { if ( req . method . toLowerCase ( ) === 'get' ) { req . body = { } ; return next ( ) ; } if ( ! req . body ) throw new InvalidPayloadException ( 'Payload in body is required' ) ; if ( req . singleton ) return next ( ) ; let batchSchema = Joi . object ( ) . keys ( { keys : Joi . array ( ) . items ( Joi . alternatives ( Joi . string ( ) , Joi . number ( ) ) ) , query : Joi . object ( ) . unknown ( ) , } ) ; if ( scope !== 'read' ) { batchSchema = batchSchema . xor ( 'query' , 'keys' ) ; } if ( scope === 'update' ) { batchSchema = batchSchema . keys ( { data : Joi . object ( ) . unknown ( ) . required ( ) , } ) ; } if ( scope === 'delete' && Array . isArray ( req . body ) ) { return next ( ) ; } const { error } = batchSchema . validate ( req . body ) ; if ( error ) { throw new FailedValidationException ( error . details [ 0 ] ) ; } if ( scope === 'read' && req . body . query ) { req . sanitizedQuery = sanitizeQuery ( req . body . query , req . accountability ) ; } return next ( ) ; } ) ;