diff --git a/lib/core.ts b/lib/core.ts index 6ceedf541..8d60c832e 100644 --- a/lib/core.ts +++ b/lib/core.ts @@ -130,6 +130,7 @@ export interface CurrentOptions { defaultMeta?: string | AnySchemaObject validateSchema?: boolean | "log" addUsedSchema?: boolean + noCache?: boolean inlineRefs?: boolean | number passContext?: boolean loopRequired?: number @@ -701,7 +702,8 @@ export default class Ajv { meta?: boolean, baseId?: string, validateSchema = this.opts.validateSchema, - addSchema = this.opts.addUsedSchema + addSchema = this.opts.addUsedSchema, + noCache = this.opts.noCache ): SchemaEnv { let id: string | undefined const {schemaId} = this.opts @@ -711,14 +713,14 @@ export default class Ajv { if (this.opts.jtd) throw new Error("schema must be object") else if (typeof schema != "boolean") throw new Error("schema must be object or boolean") } - let sch = this._cache.get(schema) + let sch = this._cache.get(schema) ?? this.schemas[normalizeId(baseId || id)] if (sch !== undefined) return sch baseId = normalizeId(id || baseId) const localRefs = getSchemaRefs.call(this, schema, baseId) sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs}) - this._cache.set(sch.schema, sch) - if (addSchema && !baseId.startsWith("#")) { + if (!noCache) this._cache.set(sch.schema, sch) + if (!noCache && addSchema && !baseId.startsWith("#")) { // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) if (baseId) this._checkUnique(baseId) this.refs[baseId] = sch diff --git a/spec/ajv.spec.ts b/spec/ajv.spec.ts index 31497935f..fffb214f5 100644 --- a/spec/ajv.spec.ts +++ b/spec/ajv.spec.ts @@ -37,6 +37,18 @@ describe("Ajv", () => { v1.should.equal(v2) }) + it("should not cache compiled functions for the same schema when opt.noCache", () => { + ajv = new _Ajv({keywords: ["foo"], allowUnionTypes: true, noCache: true}) + const schema = { + $id: "//e.com/int.json", + type: "integer", + minimum: 1, + } + const v1 = ajv.compile(schema) + const v2 = ajv.compile(schema) + v1.should.not.equal(v2) + }) + it("should throw if different schema has the same id", () => { ajv.compile({$id: "//e.com/int.json", type: "integer"}) should.throw(() => { diff --git a/spec/standalone.spec.ts b/spec/standalone.spec.ts index 45e3dad18..ec68ac879 100644 --- a/spec/standalone.spec.ts +++ b/spec/standalone.spec.ts @@ -129,6 +129,16 @@ describe("standalone code generation", () => { assert.strictEqual(Object.keys(m).length, 2) testExports(m) }) + + it("should generate module code with all exports when noCache option enabled", () => { + ajv = new _Ajv({code: {source: true}, noCache: true}) + ajv.addSchema(numSchema, "validateNumber") + ajv.addSchema(strSchema, "validateString") + const moduleCode = standaloneCode(ajv) + const m = requireFromString(moduleCode) + assert.strictEqual(Object.keys(m).length, 2) + testExports(m) + }) }) function testExports(m: {[n: string]: AnyValidateFunction}) {