Skip to content

Commit

Permalink
fix: omit title for relation schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
jannyHou committed Apr 14, 2020
1 parent be48016 commit 694a9eb
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// License text available at https://opensource.org/licenses/MIT

import {
Entity,
hasMany,
Model,
model,
property,
Expand Down Expand Up @@ -246,6 +248,61 @@ describe('build-schema', () => {
expect(schema.definitions).to.be.undefined();
});

it('relation model definition does not inherit title from source model', () => {
@model()
class Child extends Entity {
@property({
type: 'string',
})
name?: string;
}
@model()
class Parent extends Entity {
@hasMany(() => Child)
children: Child[];

@property({
type: 'string',
})
benchmarkId?: string;

@property({
type: 'string',
})
color?: string;

constructor(data?: Partial<Parent>) {
super(data);
}
}
const schema = modelToJsonSchema(Parent, {
title: 'ParentWithItsChildren',
includeRelations: true,
});
expect(schema.properties).to.containEql({
children: {
type: 'array',
// The reference here should be `ChildWithRelations`,
// instead of `ParentWithItsChildren`
items: {$ref: '#/definitions/ChildWithRelations'},
},
benchmarkId: {type: 'string'},
color: {type: 'string'},
});
// The recursive calls should NOT inherit
// `title` from the previous call's `options`.
// So the `title` here is `ChildWithRelations`
// instead of `ParentWithItsChildren`.
expect(schema.definitions).to.containEql({
ChildWithRelations: {
title: 'ChildWithRelations',
description: '(Schema options: { includeRelations: true })',
properties: {name: {type: 'string'}},
additionalProperties: false,
},
});
});

it('allows model inheritance', () => {
@model()
class User {
Expand Down
11 changes: 10 additions & 1 deletion packages/repository-json-schema/src/build-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,16 @@ export function modelToJsonSchema<T extends object>(
result.properties = result.properties ?? {};
const relMeta = meta.relations[r];
const targetType = resolveType(relMeta.target);
const targetSchema = getJsonSchema(targetType, options);

const targetOptions = {...options};
if (targetOptions.title) {
// `title` is the unique identity of a schema,
// it should be removed from the `options`
// when generating the relation schemas
delete targetOptions.title;
}

const targetSchema = getJsonSchema(targetType, targetOptions);
const targetRef = {$ref: `#/definitions/${targetSchema.title}`};
const propDef = getNavigationalPropertyForRelation(relMeta, targetRef);

Expand Down

0 comments on commit 694a9eb

Please sign in to comment.