Skip to content
Open
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
62 changes: 61 additions & 1 deletion packages/openapi-v3/src/__tests__/unit/json-to-schema.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

import {JsonSchema} from '@loopback/repository-json-schema';
import {expect} from '@loopback/testlab';
import {jsonOrBooleanToJSON, jsonToSchemaObject, SchemaObject} from '../..';
import {
ISpecificationExtension,
jsonOrBooleanToJSON,
jsonToSchemaObject,
SchemaObject,
} from '../..';

describe('jsonToSchemaObject', () => {
it('does nothing when given an empty object', () => {
Expand Down Expand Up @@ -39,6 +44,61 @@ describe('jsonToSchemaObject', () => {
propertyConversionTest(allOfDef, expectedAllOf);
});

it('convert description with relation to x-relationships', () => {
const descriptionWithRelation: JsonSchema & ISpecificationExtension = {
description:
'(tsType: ProductWithRelations, schemaOptions: { includeRelations: true }), ',
'x-relationships': {
products: {
description: 'Category have many Product.',
items: {
$ref: '#/definitions/ProductWithRelations',
},
type: 'array',
'x-foreign-keys': {
categoryId: 'Category',
},
'x-relation-type': 'hasMany',
},
},
};
type Relationship = {
description?: string;
type?: string;
$ref?: string;
items?: {$ref: string};
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-foreign-keys'?: {[x: string]: string};
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-relation-type'?: string;
};
const expectedDescriptionWithRelation: SchemaObject & {
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-relationships': {[x: string]: Relationship};
} = {
description:
'(tsType: ProductWithRelations, schemaOptions: { includeRelations: true }), ',
'x-relationships': {
products: {
description: 'Category have many Product.',
items: {
$ref: '#/definitions/ProductWithRelations',
},
type: 'array',
'x-foreign-keys': {
categoryId: 'Category',
},
'x-relation-type': 'hasMany',
},
},
'x-typescript-type': 'ProductWithRelations',
};
propertyConversionTest(
descriptionWithRelation,
expectedDescriptionWithRelation,
);
});

it('converts anyOf', () => {
const anyOfDef: JsonSchema = {
anyOf: [typeDef, typeDef],
Expand Down
7 changes: 7 additions & 0 deletions packages/openapi-v3/src/json-to-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import {JsonSchema} from '@loopback/repository-json-schema';
import _ from 'lodash';
import {
ISpecificationExtension,
isSchemaObject,
ReferenceObject,
SchemaObject,
Expand Down Expand Up @@ -130,6 +131,12 @@ export function jsonToSchemaObject(
}
break;
}
case 'x-relationships': {
result['x-relationships'] = (
json as JsonSchema & ISpecificationExtension
)['x-relationships'];
break;
}
default: {
result[property] = json[property as keyof JsonSchema];
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
modelToJsonSchema,
} from '../..';
import {expectValidJsonSchema} from '../helpers/expect-valid-json-schema';
import {SpecificationExtension} from '../../types';

describe('build-schema', () => {
describe('modelToJsonSchema', () => {
Expand Down Expand Up @@ -1140,7 +1141,7 @@ describe('build-schema', () => {
products?: Product[];
}

const expectedSchema: JsonSchema = {
const expectedSchema: JsonSchema & SpecificationExtension = {
definitions: {
Product: {
title: 'Product',
Expand All @@ -1163,6 +1164,17 @@ describe('build-schema', () => {
},
additionalProperties: false,
title: 'CategoryWithRelations',
'x-relationships': {
products: {
description: 'Category have many Product.',
type: 'array',
items: {$ref: '#/definitions/Product'},
'x-foreign-key': {categoryId: 'Category'},
'x-relation-type': 'hasMany',
'x-source-model': 'Category',
'x-target-model': 'Product',
},
},
type: 'object',
description:
`(tsType: CategoryWithRelations, ` +
Expand All @@ -1187,7 +1199,7 @@ describe('build-schema', () => {
@hasMany(() => Product)
products?: Product[];
}
const expectedSchema: JsonSchema = {
const expectedSchema: JsonSchema & SpecificationExtension = {
definitions: {
Product: {
title: 'Product',
Expand All @@ -1211,6 +1223,21 @@ describe('build-schema', () => {
description:
`(tsType: CategoryWithoutPropWithRelations, ` +
`schemaOptions: { includeRelations: true })`,
'x-relationships': {
products: {
description: 'CategoryWithoutProp have many Product.',
'x-foreign-key': {
categorywithoutpropId: 'CategoryWithoutProp',
},
items: {
$ref: '#/definitions/Product',
},
'x-relation-type': 'hasMany',
'x-source-model': 'CategoryWithoutProp',
'x-target-model': 'Product',
type: 'array',
},
},
};

// To check for case when there are no other properties than relational
Expand Down
114 changes: 114 additions & 0 deletions packages/repository-json-schema/src/build-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {inspect} from 'util';
import {JsonSchema} from './index';
import {JSON_SCHEMA_KEY} from './keys';
const debug = debugFactory('loopback:repository-json-schema:build-schema');
import {SpecificationExtension} from './types';

export interface JsonSchemaOptions<T extends object> {
/**
Expand Down Expand Up @@ -596,6 +597,24 @@ export function modelToJsonSchema<T extends object>(
result.additionalProperties = meta.settings.strict === false;
debug(' additionalProperties?', result.additionalProperties);

type Relationship = {
description?: string;
type?: string;
$ref?: string;
items?: {$ref: string};
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-foreign-key'?: {[x: string]: string};
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-relation-type'?: string;
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-source-model'?: string;
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-target-model'?: string;
// eslint-disable-next-line @typescript-eslint/naming-convention
'x-include-relations'?: string;
};
const relationships: {[x: string]: Relationship} = {};

if (options.includeRelations) {
for (const r in meta.relations) {
result.properties = result.properties ?? {};
Expand All @@ -620,6 +639,101 @@ export function modelToJsonSchema<T extends object>(
.keyFrom as JsonSchema;
}

const foreignKey: {[x: string]: string} = {};

if (!relationships[relMeta.name]) {
relationships[relMeta.name] = {};
}

if (relMeta.type === 'belongsTo') {
let keyFrom = (relMeta as {keyFrom: string}).keyFrom;
if (!keyFrom) {
keyFrom = targetType.name.toLowerCase() + 'Id';
}
foreignKey[keyFrom] = targetType.name;
relationships[relMeta.name].description =
`${relMeta.source.name} belongs to ${targetType.name}.`;
relationships[relMeta.name].type = 'object';
relationships[relMeta.name].$ref =
`#/definitions/${targetSchema.title}`;
}
if (relMeta.type === 'hasMany') {
const through = (
relMeta as {through?: {keyTo?: string; keyFrom?: string}}
).through;
if ((relMeta as {through: object}).through) {
const keyTo = through?.keyTo ?? targetType.name.toLowerCase() + 'Id';
const keyFrom =
through?.keyFrom ?? relMeta.source.name.toLowerCase() + 'Id';

foreignKey[keyTo] = targetType.name;
foreignKey[keyFrom] = relMeta.source.name;

relationships[relMeta.name].description =
`${relMeta.source.name} have many ${targetType.name}.`;
relationships[relMeta.name].type = 'object';
relationships[relMeta.name].$ref =
`#/definitions/${targetSchema.title}`;
} else {
const keyFrom =
(relMeta as {keyFrom?: string}).keyFrom ??
relMeta.source.name.toLowerCase() + 'Id';
foreignKey[keyFrom] = relMeta.source.name;
relationships[relMeta.name].description =
`${relMeta.source.name} have many ${targetType.name}.`;
relationships[relMeta.name].type = 'array';
relationships[relMeta.name].items = {
$ref: `#/definitions/${targetSchema.title}`,
};
}
}

if (relMeta.type === 'hasOne') {
let keyTo = (relMeta as {keyTo: string}).keyTo;

if (!keyTo) {
keyTo = relMeta.source.name.toLowerCase() + 'Id';
}
foreignKey[keyTo] = relMeta.source.name;
relationships[relMeta.name].description =
`${relMeta.source.name} have one ${targetType.name}.`;
relationships[relMeta.name].type = 'object';
relationships[relMeta.name].$ref =
`#/definitions/${targetSchema.title}`;
}

if (relMeta.type === 'referencesMany') {
let keyFrom = (relMeta as {keyFrom: string}).keyFrom;
if (!keyFrom) {
keyFrom = targetType.name.toLowerCase() + 'Ids';
}
foreignKey[keyFrom] = targetType.name;
relationships[relMeta.name].description =
`${relMeta.source.name} references many ${targetType.name}.`;
relationships[relMeta.name].type = 'array';
relationships[relMeta.name].items = {
$ref: `#/definitions/${targetSchema.title}`,
};
}
// Attach OpenAPI vendor extension metadata for relationship type and foreign keys
relationships[relMeta.name]['x-foreign-key'] = foreignKey;
relationships[relMeta.name]['x-relation-type'] = relMeta.type;
relationships[relMeta.name]['x-source-model'] = relMeta.source.name;
relationships[relMeta.name]['x-target-model'] = targetType.name;
if (targetOptions.includeRelations) {
relationships[relMeta.name]['x-include-relations'] =
targetOptions.includeRelations;
}
// Safely merge newly generated relationships with any existing ones on the target schema,
// casting through SpecificationExtension to satisfy TypeScript strict record constraints.
const existingRelations = (result as JsonSchema & SpecificationExtension)[
'x-relationships'
] as Record<string, unknown> | undefined;

(result as JsonSchema & SpecificationExtension)['x-relationships'] = {
...relationships,
...existingRelations,
};
includeReferencedSchema(targetSchema.title!, targetSchema);
}
}
Expand Down
8 changes: 8 additions & 0 deletions packages/repository-json-schema/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Local definition for OpenAPI specification extensions (vendor extensions starting with 'x-').
* Defined locally in repository-json-schema to avoid creating an upward dependency
* on higher-level packages like @loopback/openapi-v3.
*/
export interface SpecificationExtension {
[key: `x-${string}`]: unknown;
}
Loading