ajv-validator/ajv

console.log cannot be used as a default

bruceferguson2 opened this issue · 1 comments

What version of Ajv are you using? Does the issue happen if you use the latest version?

8.16.0

Ajv options object

{allErrors: true, useDefaults: true}

JSON Schema

{
  type: "object",
  properties: {
    report: {default: console.log}
  }
}

Sample data

Your code

import Ajv from "ajv";

const ajv = new Ajv({allErrors: true, useDefaults: true});

ajv.addKeyword({
  valid: true,
  keyword: "report",
});

const schema = {
  type: "object",
  properties: {
    report: {default: console.log}
  }
}

const validator = ajv.compile(schema);

Validation result, data AFTER validation, error messages

/home/me/apps/dbtest/node_modules/ajv/dist/compile/codegen/code.js:135
        .replace(/\u2028/g, "\\u2028")
        ^

TypeError: Cannot read properties of undefined (reading 'replace')
    at safeStringify (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/codegen/code.js:135:9)
    at stringify (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/codegen/code.js:130:22)
    at assignDefault (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/defaults.js:33:82)
    at assignDefaults (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/defaults.js:10:13)
    at iterateKeywords (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/index.js:218:39)
    at groupKeywords (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/index.js:200:13)
    at /home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/index.js:192:13
    at CodeGen.code (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/codegen/index.js:439:13)
    at CodeGen.block (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/codegen/index.js:568:18)
    at schemaKeywords (/home/ubuntu/apps/dbtest/node_modules/ajv/dist/compile/validate/index.js:190:9)

Node.js v20.10.0

What results did you expect?

That "console.log" would be used as the default value.

Are you going to resolve the issue?

JSON Schema can only deal with data that can ultimately be serialised as a JSON string. Functions cannot be represented in JSON so you won't be able to use a function like log as a default, nor as a value within JSON. For example, try JSON.stringify({func: console.log}) and you'll see it doesn't work.