Appearance
Validators Overview
A generic backend has its trades-offs. The Codedraw generic template allows you to add custom validators to your backend. This is useful when you want to add custom validation logic to your backend to prevent certain records from being created, updated, deleted or accessed unless your validation criteria are met.
Validators are entity specific so you can add a custom validator per http method and entity. For instance I have a job
entity in my application, to configure it I would do the following:
typescript
app.use('*', installSDK({
/**
* Configure your custom validators here
*/
validators: {
// this runs on every request
'*': MyGlobalValidator
createRecord: {
book: CreateBookValidator,
},
updateRecord: {
book: UpdateBookValidator,
},
deleteRecord: {
book: DeleteBookValidator,
},
getRecord: {
book: GetBookValidator,
}
},
}))
Structure
At its core A Codedraw validator is a method that takes in an input and either throws an error or resolve with an empty promise. Here is a simple Validator definition:
typescript
import { Environment, Variables } from '@/context'
export const SimpleValidator: (arg: { context: Context<Environment, Variables> }) => Promise<void> = async (
args: { context: Context<Environment, Variables> },
) => {
/**
* Your validator logic here
*/
}
Here is a simple validator implementation:
typescript
//...
if (notValid) {
throw new ResponseError(400, 'bad request')
}
return Promise.resolve()
//...
Types
Here are the types that you can use to write your validators:
typescript
/**
* The argument type of a validator function
*/
type ValidatorArgs<E extends Record<string, any>, V extends Record<string, any>> = {
// gives you a handle on the request context including environment and variables
context: Context<E, V>;
}