extending ajv with ajv-formats
-
Hi everyone,
i need to do some json schema validation with ajv and would need the "ajv-formats" extension (https://ajv.js.org/packages/ajv-formats.html) for checking for email and date data types. since version 7 those are separated from the main ajv module. I think this library would also be very useful for "n8n as API" use cases, would you consider adding it? Or do i have to do and maintain this myself - if possible at all?Best,
Dominik -
@dominikjannis If you can install the extension anywhere else, then copy the relevant files where N8N would expect them to be, that is a way of inserting the extension.
The next question is if the place where the extension folder is expected is on the read-only volume (/app/code) or the /app/data writable one.
If needed, check if that directory is settable by environment variables to make it work.
-
@dominikjannis so do you need then the
ajv
or theajv-formats
node module to be installed or both? I am not 100% sure how they are to be used within n8n, but since they seems quite popular, we can add them or just one of them to the app package itself.Also it looks like in order to use node_modules within the code node one has to explicitly enable them via
NODE_FUNCTION_ALLOW_EXTERNAL
https://docs.n8n.io/hosting/configuration/#use-built-in-and-external-modules-in-the-code-node ?Also do you have a code snippet to be used within the code node to verify those modules work?
-
-
@nebulon the ajv module itself is present, since standalone ajv works when enabled explicitly via the .env - just as you pointed it out.
we use it to check incoming data from other internal services for potentially malformed data structures before further processing. Checking for (custom) string formats would be handyhere a snippet, based off of the example from ajv for the code node:
const Ajv = require("ajv"); const addFormats = require("ajv-formats") const ajv = new Ajv(); addFormats(ajv); const schema = { type: "object", properties: { foo: { type: "integer" }, bar: { type: "string", format: "email" }, }, required: ["foo"], additionalProperties: false, }; const data = { foo: 1, bar: "no.email.com" }; const valid = ajv.validate(schema, data); if (!valid) { console.log(ajv.errors); return ajv.errors; } return data;
this should result in this error, showing everything is working:
{ instancePath: '/bar', schemaPath: '#/properties/bar/format', keyword: 'format', params: { format: 'email' }, message: 'must match format "email"' }
-