Skip to content

Commit

Permalink
Merge pull request #7 from hckrnews/feature/first-draft
Browse files Browse the repository at this point in the history
Make AJV options customizable
  • Loading branch information
w3nl authored Nov 22, 2023
2 parents fa447f8 + 0ea8426 commit 072787d
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 9 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,14 @@ const schema = {
required: ['foo'],
additionalProperties: false
}
const ExampleModel = openapiToModel(schema)

const options = {
validate: true,
strict: false,
extraAjvFormats: ['date-time']
}

const ExampleModel = openapiToModel(schema, options)

// Create an empty model, with the default values
const example = new ExampleModel()
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@hckrnews/openapi-model",
"description": "OpenAPI Model",
"version": "0.2.2",
"version": "0.2.3",
"author": {
"name": "Pieter Wigboldus",
"url": "https://hckr.news/"
Expand Down Expand Up @@ -64,4 +64,4 @@
"semver": "^7.5.3",
"xml2js": "^0.5.0"
}
}
}
11 changes: 7 additions & 4 deletions src/model.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import Ajv from 'ajv'
import addFormats from 'ajv-formats'
const ajv = new Ajv({
strict: false
})
addFormats(ajv, ['date', 'time', 'uri', 'uuid', 'email', 'hostname', 'regex'])

const defaultExtraAjvFormats = ['date', 'time', 'uri', 'uuid', 'email', 'hostname', 'regex']
/**
* @typedef {import('./schema.d.ts').OpenAPIV3.BaseSchemaObject} BaseSchemaObject
* @typedef {import('./schema.d.ts').OpenAPIV3.SchemaObject} SchemaObject
Expand Down Expand Up @@ -43,6 +40,12 @@ const createBaseObjectFromSchema = (schema) => Object.fromEntries(
const openapiToModel = (schema, options = {}) => {
const { validate = true } = options
const emptyObject = createBaseObjectFromSchema(schema)

const ajv = new Ajv({
strict: options.strict || false
})
const extraAjvFormats = options.extraAjvFormats || []
addFormats(ajv, [...defaultExtraAjvFormats, ...extraAjvFormats])
const compile = ajv.compile(schema)

class Model {
Expand Down
2 changes: 2 additions & 0 deletions src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export declare namespace OpenAPIV3 {

export interface Options {
validate?: boolean;
strict?: boolean;
extraAjvFormats?: any[];
}
export class Model {
constructor(data?: object);
Expand Down

0 comments on commit 072787d

Please sign in to comment.