Extending Class Schemas
When working with OpenAPI schemas in InversifyJS HTTP, you might need to create schemas that extend from a base schema. This is useful for creating inheritance hierarchies where child schemas include all properties from a parent schema plus additional properties.
Basic Schema Extension
To extend a class schema, you can use the @OasSchema decorator with a function that takes a ToSchemaFunction parameter. This function allows you to reference other schema classes.
@OasSchema()
export class BaseSchema {
@OasSchemaProperty({
description: 'A common string property',
type: 'string',
})
public foo!: string;
}
@OasSchema((toSchema: ToSchemaFunction) => toSchema(BaseSchema), {
customAttributes: {
unevaluatedProperties: false,
},
})
export class ExtendedSchema extends BaseSchema {
@OasSchemaProperty({
description: 'An additional property in the extended schema',
type: 'string',
})
public bar!: string;
@OasSchemaProperty({
description: 'A numeric property in the extended schema',
minimum: 0,
type: 'number',
})
public count!: number;
}
How It Works
-
Base Schema: The
BaseSchemaclass is decorated with@OasSchemaand includes thefooproperty decorated with@OasSchemaProperty. -
Extended Schema: The
ExtendedSchemaclass:- Extends
BaseSchemausing TypeScript inheritance (extends BaseSchema) - Uses
@OasSchema((toSchema: ToSchemaFunction) => toSchema(BaseSchema))to reference the base schema in the OpenAPI specification - Adds additional properties (
barandcount) with their own@OasSchemaPropertydecorators
- Extends
-
OpenAPI Generation: This generates an OpenAPI schema where:
- The base schema is defined with its properties
- The extended schema uses
allOfwith a reference ($ref) to the base schema - The extended schema includes its own properties in addition to the inherited ones