Validation du schéma JSON pour h3, à l'aide de typebox et ajv.
# Using npm
npm install h3-typebox
# Using yarn
yarn install h3-typebox
# Using pnpm
pnpm install h3-typebox
import { createServer } from 'http'
import { createApp } from 'h3'
import { validateBody , validateQuery , Type } from 'h3-typebox'
const app = createApp ( )
app . use ( '/' , async ( event ) => {
// Validate body
const body = await validateBody ( event , Type . Object ( {
optional : Type . Optional ( Type . String ( ) ) ,
required : Type . Boolean ( ) ,
} ) )
// Validate query
const query = validateQuery ( event , Type . Object ( {
required : Type . String ( ) ,
} ) )
} )
createServer ( app ) . listen ( process . env . PORT || 3000 )
Découvrez comment définir votre schéma avec la documentation Type
sur TypeBox.
Vous pouvez définir un objet d'options sur validateBody
ou validateQuery
. Actuellement, les options suivantes sont prises en charge :
includeAjvFormats: Boolean
Certains formats comme date
, date-time
ou email
sont spécifiés dans le brouillon JSONSchema actuel, mais ne sont pas inclus par défaut dans ajv, mais sont fournis par le package ajv-formats
. Si l'un de ces formats est nécessaire, vous pouvez spécifier includeAjvFormats: true
dans les options de validateBody
ou validateQuery
comme ceci :
// Body
validateBody ( event , schema , { includeAjvFormats : true } )
// Query
validateQuery ( event , schema , { includeAjvFormats : true } )
Actuellement, seuls les formats étendus suivants sont pris en charge pour des raisons de performances et de sécurité :
Ceux-ci peuvent être utilisés par des schémas personnalisés avec la méthode Type.Unsafe
ou avec un schéma en ligne :
const bodySchema = Type . Object ( {
optional : Type . Optional ( Type . String ( ) ) ,
dateTime : Type . String ( { format : 'date-time' } )
} )
validateBody ( event , bodySchema , { includeAjvFormats : true } )
pnpm install
pnpm dev
Fabriqué avec ?
Publié sous licence MIT.