@trojs/openapi-model 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 TroJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # OpenAPI Model
2
+
3
+ [![NPM version][npm-image]][npm-url] [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=coverage)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model)
4
+ [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=bugs)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=sqale_index)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model)
5
+ [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=hckrnews_openapi-model&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=hckrnews_openapi-model)
6
+
7
+ Create easy a Model from a OpenAPI spec.
8
+
9
+ ## Installation
10
+
11
+ `npm install @trojs/openapi-model`
12
+ or
13
+ `yarn add @trojs/openapi-model`
14
+
15
+ ## Test the package
16
+
17
+ `npm run test`
18
+ or
19
+ `yarn test`
20
+
21
+ ## How to use
22
+
23
+ ```javascript
24
+ const schema = {
25
+ type: 'object',
26
+ properties: {
27
+ foo: {
28
+ type: 'string',
29
+ default: 'bar'
30
+ }
31
+ },
32
+ required: ['foo'],
33
+ additionalProperties: false
34
+ }
35
+
36
+ const options = {
37
+ validate: true,
38
+ strict: false,
39
+ extraAjvFormats: ['date-time']
40
+ }
41
+
42
+ const ExampleModel = openapiToModel(schema, options)
43
+
44
+ // Create an empty model, with the default values
45
+ const example = new ExampleModel()
46
+ /*
47
+ {
48
+ foo: 'bar'
49
+ }
50
+ */
51
+
52
+ // Create a model with the default values, but overwrite the given properties
53
+ const example2 = new ExampleModel({
54
+ foo: 'It works!'
55
+ })
56
+ /*
57
+ {
58
+ foo: 'It works!'
59
+ }
60
+ */
61
+
62
+ // Create a model with the default values, but overwrite the given properties
63
+ const example2 = new ExampleModel({
64
+ foo: 3.14
65
+ })
66
+ /*
67
+ Throws an Error because the type is wrong
68
+
69
+ error.message
70
+ "Invalid data"
71
+
72
+ error.errors
73
+ [
74
+ {
75
+ instancePath: '/foo',
76
+ keyword: 'type',
77
+ message: 'must be string',
78
+ params: {
79
+ type: 'string'
80
+ },
81
+ schemaPath: '#/properties/foo/type'
82
+ }
83
+ ]
84
+
85
+ error.schema
86
+ {
87
+ type: 'object',
88
+ properties: {
89
+ foo: {
90
+ type: 'string',
91
+ default: 'bar'
92
+ }
93
+ },
94
+ required: ['foo'],
95
+ additionalProperties: false
96
+ }
97
+
98
+ // The object that is send to the model
99
+ error.data
100
+ {
101
+ foo: 3.14
102
+ }
103
+
104
+ // The object that is send to the model, but also with the default values
105
+ error.newData
106
+ {
107
+ foo: 3.14
108
+ }
109
+ */
110
+ ```
111
+
112
+
113
+ [npm-url]: https://www.npmjs.com/package/@trojs/openapi-model
114
+ [npm-image]: https://img.shields.io/npm/v/@trojs/openapi-model.svg
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@trojs/openapi-model",
3
+ "description": "OpenAPI Model",
4
+ "version": "0.5.0",
5
+ "author": {
6
+ "name": "Pieter Wigboldus",
7
+ "url": "https://trojs.org/"
8
+ },
9
+ "license": "MIT",
10
+ "scripts": {
11
+ "lint": "eslint src/*.js --config .eslintrc",
12
+ "lint:report": "eslint src/*.js --config .eslintrc -f json -o report.json",
13
+ "lint:fix": "eslint src/*.js --config .eslintrc --fix",
14
+ "lint:rules": "eslint --print-config file.js > eslintconfig.json",
15
+ "test": "node --test src/*.test.js",
16
+ "test:watch": "node --watch --test src/*.test.js",
17
+ "test:coverage": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info src/*.test.js",
18
+ "cpd": "node_modules/jscpd/bin/jscpd src",
19
+ "vulnerabilities": "npm audit --omit=dev"
20
+ },
21
+ "type": "module",
22
+ "files": [
23
+ "src/model.js",
24
+ "src/schema.d.ts"
25
+ ],
26
+ "main": "src/model.js",
27
+ "types": "src/schema.d.ts",
28
+ "devDependencies": {
29
+ "@hckrnews/eslint-config": "^3.0.0",
30
+ "eslint": "^8.23.0",
31
+ "eslint-config-standard": "^17.1.0",
32
+ "eslint-plugin-import": "^2.26.0",
33
+ "eslint-plugin-jsdoc": "^48.0.0",
34
+ "eslint-plugin-n": "^16.0.0",
35
+ "eslint-plugin-promise": "^6.0.1",
36
+ "eslint-plugin-sonarjs": "^0.23.0",
37
+ "jscpd": "^3.2.1"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/hckrnews/openapi-model"
42
+ },
43
+ "engines": {
44
+ "node": ">= 18.13"
45
+ },
46
+ "keywords": [
47
+ "openapi",
48
+ "model",
49
+ "entity",
50
+ "schema",
51
+ "specification",
52
+ "api",
53
+ "ajv"
54
+ ],
55
+ "dependencies": {
56
+ "@trojs/deep-merge": "^0.4.0",
57
+ "ajv": "^8.12.0",
58
+ "ajv-formats": "^2.1.1"
59
+ },
60
+ "funding": {
61
+ "type": "github",
62
+ "url": "https://github.com/sponsors/w3nl"
63
+ },
64
+ "overrides": {
65
+ "semver": "^7.5.3",
66
+ "xml2js": "^0.6.0"
67
+ }
68
+ }
package/src/model.js ADDED
@@ -0,0 +1,104 @@
1
+ import Ajv from 'ajv'
2
+ import addFormats from 'ajv-formats'
3
+ import { deepMerge } from '@trojs/deep-merge'
4
+
5
+ const defaultExtraAjvFormats = ['date', 'time', 'uri', 'uuid', 'email', 'hostname', 'regex']
6
+ /**
7
+ * @typedef {import('./schema.d.ts').OpenAPIV3.BaseSchemaObject} BaseSchemaObject
8
+ * @typedef {import('./schema.d.ts').OpenAPIV3.SchemaObject} SchemaObject
9
+ * @typedef {import('./schema.d.ts').Options} Options
10
+ * @typedef {import('./schema.d.ts').Model} Model
11
+ */
12
+
13
+ /**
14
+ * @param {[key: string, schema: SchemaObject]} params
15
+ * @returns {[key: string, defaultValue: any]}
16
+ */
17
+ const createPropertyWithDefaultValue = ([key, schema]) => {
18
+ const { type, default: defaultValue } = schema
19
+
20
+ if (type === 'object') {
21
+ const subParser = createBaseObjectFromSchema(schema)
22
+ return [key, subParser]
23
+ }
24
+
25
+ return [key, defaultValue]
26
+ }
27
+
28
+ /**
29
+ * @param {BaseSchemaObject|SchemaObject} schema
30
+ * @returns {object}
31
+ */
32
+ const createBaseObjectFromSchema = (schema) => Object.fromEntries(
33
+ Object.entries(schema.properties).map(createPropertyWithDefaultValue)
34
+ )
35
+
36
+ const openapiToModel = (schema, options = {}) => {
37
+ const { validate = true } = options
38
+ const emptyObject = createBaseObjectFromSchema(schema)
39
+
40
+ const ajv = new Ajv({
41
+ strict: options.strict || false
42
+ })
43
+ const extraAjvFormats = options.extraAjvFormats || []
44
+ addFormats(ajv, [...defaultExtraAjvFormats, ...extraAjvFormats])
45
+ const compile = ajv.compile(schema)
46
+
47
+ class Model {
48
+ /**
49
+ * @param {object=} data
50
+ */
51
+ constructor (data) {
52
+ this.errors = undefined
53
+ this.data = data || {}
54
+ this.schema = schema
55
+ this.emptyObject = emptyObject
56
+ }
57
+
58
+ /**
59
+ * Set the data for the model, including defaults, and validate it against the schema
60
+ * @param {object=} data
61
+ */
62
+ set data (data) {
63
+ const newData = deepMerge(emptyObject, data)
64
+ const valid = compile(newData)
65
+
66
+ if (validate && !valid) {
67
+ const error = new Error('Invalid data')
68
+ // @ts-ignore
69
+ error.errors = compile.errors
70
+ // @ts-ignore
71
+ error.schema = schema
72
+ // @ts-ignore
73
+ error.data = data
74
+ // @ts-ignore
75
+ error.newData = newData
76
+ // @ts-ignore
77
+ error.emptyObject = emptyObject
78
+ throw error
79
+ }
80
+ this.value = newData
81
+ }
82
+
83
+ /**
84
+ * @returns {object}
85
+ */
86
+ get data () {
87
+ return this.value
88
+ }
89
+
90
+ /**
91
+ * @returns {object}
92
+ */
93
+ valueOf () {
94
+ return this.value
95
+ }
96
+ }
97
+ return Model
98
+ }
99
+
100
+ export {
101
+ openapiToModel,
102
+ createBaseObjectFromSchema,
103
+ createPropertyWithDefaultValue
104
+ }
@@ -0,0 +1,52 @@
1
+ export declare namespace OpenAPIV3 {
2
+ type NonArraySchemaObjectType = 'boolean' | 'object' | 'number' | 'string' | 'integer';
3
+ type SchemaObject = NonArraySchemaObject | ArraySchemaObject;
4
+
5
+ interface ReferenceObject {
6
+ $ref: string;
7
+ }
8
+
9
+ interface ArraySchemaObject extends BaseSchemaObject {
10
+ type: ArraySchemaObjectType;
11
+ items?: ReferenceObject | SchemaObject;
12
+ }
13
+
14
+ interface NonArraySchemaObject extends BaseSchemaObject {
15
+ type: NonArraySchemaObjectType;
16
+ default?: any;
17
+ example?: any;
18
+ properties?: {
19
+ [name: string]: ReferenceObject | SchemaObject;
20
+ };
21
+ }
22
+
23
+ interface BaseSchemaObject {
24
+ default?: any;
25
+ additionalProperties?: boolean | ReferenceObject | SchemaObject;
26
+ required?: string[];
27
+ properties?: {
28
+ [name: string]: ReferenceObject | SchemaObject;
29
+ };
30
+ example?: any;
31
+ }
32
+ }
33
+
34
+ export interface Options {
35
+ validate?: boolean;
36
+ strict?: boolean;
37
+ extraAjvFormats?: any[];
38
+ }
39
+
40
+ export declare class Model {
41
+ constructor(data?: object);
42
+ data: object;
43
+ value: object;
44
+ set data(data?: object): void;
45
+ get data(): object;
46
+ valueOf(): object;
47
+ }
48
+
49
+ export function openapiToModel(
50
+ schema: BaseSchemaObject,
51
+ options?: Options
52
+ ): typeof Model;