Skip to main content

OpenAPI - Validation

In addition to automatically generating OpenAPI specs for your application, Psychic also provides built in request and response validation, leveraging the openapi specs to determine the appropriate shapes for your request body, query, headers, and response bodies.

Opting into validations

To opt into this, you can take one of two configuration actions:

1. define a global validation config

Defining a global validation config will apply to all endpoints belonging to OpenAPI-decorated controllers. To tap into the global config, open the conf/app.ts file and update your openapi configuration to include validation, like so:

// conf/app.ts
export default async (psy: PsychicApp) => {
...

psy.set('openapi', {
// ...
validate: {
headers: true,
requestBody: true,
query: true,
responseBody: AppEnv.isTest,
},
})
}

If you have multiple openapi configurations, you will need to apply validation to each one of them if you want to make sure it spreads to all the controllers leveraging it. In some cases, this is not necessary. For example, you may have one openapi spec for mobile, and one for web, but they may both cover the same endpoints. If this is the case, you don't need validation on both.

However, if you decided to have one openapi spec for your admin endpoints and one for your app endpoints, then you would probably want to apply validation rules to both. To understand more about how psychic leverages multiple openapi specs, see our multiple specs guides.

2. define validation on your OpenAPI decorator

Within the OpenAPI decorator, you can also provide the same validation options. If they are provided, psychic will merge the options with the global defaults provided, prioritizing the custom validation options over the global defaults.

// controllers/PetsController
export default class PetsController {
@OpenAPI(Pet, {
...
validate: {
headers: true,
requestBody: true,
query: true,
responseBody: AppEnv.isTest,
}
})
public async index() {
...
}
}

Customizing validation options

Psychic leverages ajv to validate openapi schemas. If you would like to customize the Ajv validator, you can provide custom overrides via ajvOptions, which will be sent through to the constructor of the imported Ajv class.

// controllers/PetsController
export default class PetsController {
@OpenAPI(Pet, {
...
validate: {
ajvOptions: {
// this is off by default, but you will
// always want to keep this off in prod
// to avoid DoS vulnerabilities
allErrors: AppEnv.isTest,

// provide a custom init function to further
// configure your ajv instance before validating
init: ajv => {
ajv.addFormat('myFormat', {
type: 'string',
validate: data => MY_FORMAT_REGEX.test(data),
})
}
}
}
})
public async index() {
...
}
}
warning

Psychic clones data before sending it into ajv, so attempting to use options which would mutate the incoming data will not take effect the way you would expect.