Skip to content

Commit

Permalink
Don't mutate a schema with a transform keyword while compiling it.
Browse files Browse the repository at this point in the history
  • Loading branch information
n-e committed May 4, 2021
1 parent b698f4b commit da3df95
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
11 changes: 11 additions & 0 deletions spec/transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,15 @@ describe('keyword "transform"', () => {
data.should.deep.equal(["ab"])
})
})

ajvs.forEach((ajv, i) => {
it(`shouldn't mutate the transform array of the schema while compiling it #${i}`, () => {
const data = {p: " trimObject "}
const schema = {type: "object", properties: {p: {type: "string", transform: ["trimLeft"]}}}
ajv.validate(schema, data).should.equal(true)
data.should.deep.equal({p: "trimObject "})

schema.properties.p.transform.should.deep.equal(["trimLeft"])
})
})
})
6 changes: 4 additions & 2 deletions src/definitions/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ function _getDef(): CodeKeywordDefinition {

function transformExpr(ts: string[]): Code {
if (!ts.length) return data
const t = ts.pop() as string
const t = ts[ts.length - 1]
const remaining = ts.slice(0, -1)

if (!(t in transform)) throw new Error(`transform: unknown transformation ${t}`)
const func = gen.scopeValue("func", {
ref: transform[t as TransformName],
code: _`require("ajv-keywords/dist/definitions/transform").transform${getProperty(t)}`,
})
const arg = transformExpr(ts)
const arg = transformExpr(remaining)
return cfg && t === "toEnumCase" ? _`${func}(${arg}, ${cfg})` : _`${func}(${arg})`
}
},
Expand Down

0 comments on commit da3df95

Please sign in to comment.