I'm trying to write a 'sign up' validator for my Express backend. I'm using AJV for this. Obviously, I want to export the validator schema as a module, so I'm following this page from the AJV documentation. However I keep getting: TypeError: standaloneCode is not a function
Here's my code:
const Ajv = require("ajv")
const ajv = new Ajv({ code: { source: true } })
const standaloneCode = require("ajv/dist/standalone")
const signupSchema = {
type: "object",
properties: {
username: { type: "string" },
email: { type: "string" },
password: { type: "string" },
confirmPassword: { type: "string" },
},
required: ["username", "email", "password", "confirmPassword"],
}
const validate = ajv.compile(signupSchema)
const moduleCode = standaloneCode(ajv, validate)
module.exports = moduleCode
Thank you in advance.
This seems to be a mistake in the AJV documentation (https://ajv.js.org/standalone.html). The bundled standalone
module has ESM style exports, so you will need to explicitly refer to .default
when using require
:
const standaloneCode = require('ajv/dist/standalone').default