Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Root $id not overrided by S.extend #54

Merged
merged 5 commits into from
Dec 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
language: node_js

node_js:
- "11.10.1" # tmp workaround https://stackoverflow.com/questions/55059748/travis-jest-typeerror-cannot-assign-to-read-only-property-symbolsymbol-tostr
- "13"
- "11"
- "10"
- "8"
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ A fluent API to generate JSON schemas (draft-07) for Node.js and browser.
- Runtime errors for invalid options or keywords misuse
- Javascript constants can be used in the JSON schema (e.g. _enum_, _const_, _default_ ) avoiding discrepancies between model and schema
- Typescript definitions
- Zero dependencies
- Coverage 99%

## Install
Expand Down Expand Up @@ -289,10 +288,11 @@ const userBaseSchema = S.object()
.prop('username', S.string())
.prop('password', S.string())

const userSchema = S.extend(userBaseSchema)
const userSchema = S.object()
.prop('id', S.string().format('uuid'))
.prop('createdAt', S.string().format('time'))
.prop('updatedAt', S.string().format('time'))
.extend(userBaseSchema)

console.log(userSchema)
```
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,8 @@
"lodash.merge": "^4.6.2",
"prettier": "^1.14.3",
"typescript": "^3.2.2"
},
"dependencies": {
"deepmerge": "^4.2.2"
}
}
1 change: 1 addition & 0 deletions src/BaseSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,7 @@ const BaseSchema = (
* @private It returns the internal schema data structure
* @returns {object}
*/
// TODO LS if we implement S.raw() we can drop this hack because from a JSON we can rebuild a fluent-schema
_getState: () => {
return schema
},
Expand Down
2 changes: 1 addition & 1 deletion src/FluentSchema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export interface ObjectSchema extends BaseSchema<ObjectSchema> {
patternProperties: (options: PatternPropertiesOptions) => ObjectSchema
dependencies: (options: DependenciesOptions) => ObjectSchema
propertyNames: (value: JSONSchema) => ObjectSchema
extend: (schema: ObjectSchema) => ObjectSchema
}

export interface MixedSchema<T> extends BaseSchema<T> {
Expand Down Expand Up @@ -145,7 +146,6 @@ export interface S extends BaseSchema<S> {
array: () => ArraySchema
object: () => ObjectSchema
null: () => NullSchema
extend: (schema: ObjectSchema) => ObjectSchema
//FIXME LS we should return only a MixedSchema
mixed: <T>(types: TYPE[]) => MixedSchema<T> & any
}
Expand Down
12 changes: 2 additions & 10 deletions src/FluentSchema.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
'use strict'
const merge = require('deepmerge')

const { FORMATS, TYPES } = require('./utils')

const { BaseSchema } = require('./BaseSchema')
Expand Down Expand Up @@ -170,16 +172,6 @@ module.exports = {
string: () => S().string(),
mixed: types => S().mixed(types),
object: () => S().object(),
extend: schema => {
if (!schema) {
throw new Error("Schema can't be null or undefined")
}
if (!schema.isFluentSchema) {
throw new Error("Schema isn't FluentSchema type")
}
const state = schema._getState()
return S().object(state)
},
array: () => S().array(),
boolean: () => S().boolean(),
integer: () => S().integer(),
Expand Down
14 changes: 14 additions & 0 deletions src/ObjectSchema.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use strict'
const merge = require('deepmerge')
const { BaseSchema } = require('./BaseSchema')
const {
omit,
Expand Down Expand Up @@ -246,6 +247,19 @@ const ObjectSchema = ({ schema = initialState, ...options } = {}) => {
})
},

extend: base => {
if (!base) {
throw new Error("Schema can't be null or undefined")
}
if (!base.isFluentSchema) {
throw new Error("Schema isn't FluentSchema type")
}
const state = base._getState()
const extended = merge(state, schema)

return ObjectSchema({ schema: extended, ...options })
},

/**
* The "definitions" keywords provides a standardized location for schema authors to inline re-usable JSON Schemas into a more general schema.
* There are no restrictions placed on the values within the array.
Expand Down
70 changes: 66 additions & 4 deletions src/ObjectSchema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -554,13 +554,21 @@ describe('ObjectSchema', () => {
describe('extend', () => {
it('extends a simple schema', () => {
const base = S.object()
.id('base')
.title('base')
.additionalProperties(false)
.prop('foo', S.string().minLength(5))

const extended = S.extend(base).prop('bar', S.number())
const extended = S.object()
.id('extended')
.title('extended')
.prop('bar', S.number())
.extend(base)

expect(extended.valueOf()).toEqual({
$schema: 'http://json-schema.org/draft-07/schema#',
$id: 'extended',
title: 'extended',
additionalProperties: false,
properties: {
foo: {
Expand All @@ -576,6 +584,7 @@ describe('ObjectSchema', () => {
})
it('extends a nested schema', () => {
const base = S.object()
.id('base')
.additionalProperties(false)
.prop(
'foo',
Expand All @@ -590,10 +599,14 @@ describe('ObjectSchema', () => {
.prop('bol', S.boolean().required())
.prop('num', S.integer().required())

const extended = S.extend(base).prop('bar', S.number())
const extended = S.object()
.id('extended')
.prop('bar', S.number())
.extend(base)

expect(extended.valueOf()).toEqual({
$schema: 'http://json-schema.org/draft-07/schema#',
$id: 'extended',
additionalProperties: false,
properties: {
foo: {
Expand Down Expand Up @@ -623,14 +636,63 @@ describe('ObjectSchema', () => {
type: 'object',
})
})
it('extends a schema with definitions', () => {
const base = S.object()
.id('base')
.additionalProperties(false)
.definition('def1', S.object().prop('some'))
.definition('def2', S.object().prop('somethingElse'))
.prop(
'foo',
S.object().prop(
'id',
S.string()
.format('uuid')
.required()
)
)
.prop('str', S.string().required())
.prop('bol', S.boolean().required())
.prop('num', S.integer().required())

const extended = S.object()
.id('extended')
.definition('def1', S.object().prop('someExtended'))
.prop('bar', S.number())
.extend(base)

expect(extended.valueOf()).toEqual({
$schema: 'http://json-schema.org/draft-07/schema#',
definitions: {
def1: { type: 'object', properties: { someExtended: {} } },
def2: { type: 'object', properties: { somethingElse: {} } },
},
type: 'object',
$id: 'extended',
additionalProperties: false,
properties: {
foo: {
type: 'object',
properties: { id: { type: 'string', format: 'uuid' } },
required: ['id'],
},
str: { type: 'string' },
bol: { type: 'boolean' },
num: { type: 'integer' },
bar: { type: 'number' },
},
required: ['str', 'bol', 'num'],
})
})

it('throws an error if a schema is not provided', () => {
expect(() => {
S.extend()
S.object().extend()
}).toThrow("Schema can't be null or undefined")
})
it('throws an error if a schema is not provided', () => {
expect(() => {
S.extend('boom!')
S.object().extend('boom!')
}).toThrow("Schema isn't FluentSchema type")
})
})
Expand Down
3 changes: 2 additions & 1 deletion src/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,11 @@ const userBaseSchema = S.object()
.prop('username', S.string())
.prop('password', S.string())

const userSchema = S.extend(userBaseSchema)
const userSchema = S.object()
.prop('id', S.string().format('uuid'))
.prop('createdAt', S.string().format('time'))
.prop('updatedAt', S.string().format('time'))
.extend(userBaseSchema)
.valueOf()

console.log(userSchema.valueOf())
9 changes: 5 additions & 4 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,19 @@ const schema = S.object()
.writeOnly(true)
.valueOf()

console.log(JSON.stringify(schema))
console.log(S.object().isFluentSchema)
console.log('example:\n', JSON.stringify(schema))
console.log('isFluentSchema:', S.object().isFluentSchema)

const userBaseSchema = S.object()
.additionalProperties(false)
.prop('username', S.string())
.prop('password', S.string())

const userSchema = S.extend(userBaseSchema)
const userSchema = S.object()
.prop('id', S.string().format('uuid'))
.prop('createdAt', S.string().format('time'))
.prop('updatedAt', S.string().format('time'))
.extend(userBaseSchema)
.valueOf()

console.log('\n user:', JSON.stringify(userSchema))
console.log('user:\n', JSON.stringify(userSchema))
2 changes: 1 addition & 1 deletion src/types/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"noEmit": true,
"noEmit": false,
"strict": true
},
"files": ["./index.ts"]
Expand Down