Skip to content

Commit

Permalink
fix: cache ajv schemas rather than ajv objects for schema validation (#…
Browse files Browse the repository at this point in the history
…3228)

* fix: cache ajv schemas rather than ajv objects for schema validation

* fix: remove lru cache and use ajv caching properly
  • Loading branch information
dbcfd authored May 15, 2024
1 parent 367f3a8 commit da53475
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
1 change: 0 additions & 1 deletion packages/stream-model-instance-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
"ajv": "^8.8.2",
"ajv-formats": "^2.1.1",
"fast-json-patch": "^3.1.0",
"least-recent": "^1.0.3",
"lodash.clonedeep": "^4.5.0",
"uint8arrays": "^5.0.1"
},
Expand Down
20 changes: 9 additions & 11 deletions packages/stream-model-instance-handler/src/schema-utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import Ajv, { SchemaObject } from 'ajv/dist/2020.js'
import addFormats from 'ajv-formats'
import { LRUCache } from 'least-recent'

const AJV_CACHE_SIZE = 500

function buildAjv(): Ajv {
const validator = new Ajv({
Expand All @@ -21,22 +18,23 @@ function buildAjv(): Ajv {
* TODO: Move schema stream loading out of this.
*/
export class SchemaValidation {
readonly validators: LRUCache<string, Ajv>
readonly ajv: Ajv

constructor() {
this.validators = new LRUCache(AJV_CACHE_SIZE)
this.ajv = buildAjv()
}

public validateSchema(content: Record<string, any>, schema: SchemaObject, schemaId: string) {
let validator = this.validators.get(schemaId)
if (!validator) {
validator = buildAjv()
this.validators.set(schemaId, validator)
let existingSchema = this.ajv.getSchema(schemaId)
if (!existingSchema) {
this.ajv.addSchema(schema, schemaId)
//we've added the schema above, so ajv will have it
existingSchema = this.ajv.getSchema(schemaId)!
}
const isValid = validator.validate(schema, content)
const isValid = existingSchema(content)

if (!isValid) {
const errorMessages = validator.errorsText()
const errorMessages = this.ajv.errorsText(existingSchema.errors)
throw new Error(`Validation Error: ${errorMessages}`)
}
}
Expand Down

0 comments on commit da53475

Please sign in to comment.