Appearance
Validators Example
In this example I have an app that allows users to add their favourite book. I want to make sure the user is entitled to use this api before the book can be created.
- Step one create a function
typescript
import { ValidatorArgs as Args, SRI, ResponseError } from '@coderpunktech/codedraw-core'
import { Environment, Variables } from '@/context'
export const EntitlementValidator = (args: Args<Environment, Variables>): Promise<void> => {
const sri: SRI.SRI = args.context.get('sri')!
const accountId = args.context.get('jwtPayload')!.sub
const resourceManager: ResourceManager = args.context.get('resourceManager')!
// leave the identifier empty we only care about the name being defined in this case
const entitlementSri: SRI.SRI = SRI.build('entitlement', { identifier: '__' })
const entitlement = await resourceManager.getCollection<any>(entitlementSri).findOne({ account_id: accountId })
if (!entitlement) {
throw new ResponseError(403, 'Not entitled')
}
return Promise.resolve()
}
- Step two configure the validator
typescript
//...
import { EntitlementValidator } from '@/validators/entitlement.validator'
app.use('*', installSDK({
/**
* Configure your custom validators here
*/
validators: {
createRecord: {
book: EntitlementValidator,
}
},
}))
This will ensure the validators will run everytime a client will try to create a record of entity type book
.
Close down the endpoints and only allow your custom code
typescript
import { ValidatorArgs as Args, SRI, ResponseError } from '@coderpunktech/codedraw-core'
import { Environment, Variables } from '@/context'
export const OverridesOnlyValidator = (args: Args<Environment, Variables>): Promise<void> => {
const sri: SRI.SRI = args.context.get('sri')!
if (!sri.override) {
throw new ResponseError(403, 'Only Overrides are allowed')
}
return Promise.resolve()
}
This validator will make sure only your custom code will execute for all CRUD requests. To wire it:
typescript
//...
import { EntitlementValidator } from '@/validators/entitlement.validator'
app.use('*', installSDK({
validators: {
'*': OverridesOnlyValidator,
},
}))