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

feat(metadata): handle array types and improve api property types #2001

Merged
merged 2 commits into from
Nov 14, 2024
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
5 changes: 5 additions & 0 deletions .changeset/selfish-items-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-metadata": minor
---

Handle array types and fix ApiProperty decorator type
37 changes: 33 additions & 4 deletions packages/openapi-metadata/src/loaders/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { PropertyMetadataStorage } from "../metadata/property.js";
import { schemaPath } from "../utils/schema.js";
import { isThunk } from "../utils/metadata.js";

const PrimitiveTypeLoader: TypeLoaderFn = async (_context, value) => {
export const PrimitiveTypeLoader: TypeLoaderFn = async (_context, value) => {
if (typeof value === "string") {
return { type: value };
}
Expand All @@ -28,7 +28,38 @@ const PrimitiveTypeLoader: TypeLoaderFn = async (_context, value) => {
}
};

const ClassTypeLoader: TypeLoaderFn = async (context, value) => {
export const ArrayTypeLoader: TypeLoaderFn = async (context, value) => {
if (!Array.isArray(value)) {
return;
}

if (value.length <= 0) {
context.logger.warn("You tried to specify an array type without any item");
return;
}

if (value.length > 1) {
context.logger.warn(
"You tried to specify an array type with multiple items. Please use the 'enum' option if you want to specify an enum.",
);
return;
}

const itemsSchema = await loadType(context, { type: value[0] });

// TODO: Better warn stack trace
if (!itemsSchema) {
context.logger.warn("You tried to specify an array type with an item that resolves to undefined.");
return;
}

return {
type: "array",
items: itemsSchema,
};
};

export const ClassTypeLoader: TypeLoaderFn = async (context, value) => {
if (typeof value !== "function" || !value.prototype) {
return;
}
Expand All @@ -49,8 +80,6 @@ const ClassTypeLoader: TypeLoaderFn = async (context, value) => {

if (!properties) {
context.logger.warn(`You tried to use '${model}' as a type but it does not contain any ApiProperty.`);

return;
}

context.schemas[model] = schema;
Expand Down
3 changes: 2 additions & 1 deletion packages/openapi-metadata/src/metadata/property.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { OpenAPIV3 } from "openapi-types";
import type { TypeOptions } from "../types.js";
import { createMetadataStorage } from "./factory.js";

export type PropertyMetadata = {
export type PropertyMetadata = Omit<OpenAPIV3.NonArraySchemaObject, "type" | "enum" | "properties" | "required"> & {
name: string;
required: boolean;
} & TypeOptions;
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-metadata/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export type HttpMethods = `${OpenAPIV3.HttpMethods}`;

export type PrimitiveType = OpenAPIV3.NonArraySchemaObjectType;

export type TypeValue = Function | PrimitiveType;
export type TypeValue = Function | PrimitiveType | [PrimitiveType | Function];
export type Thunk<T> = (context: Context) => T;
export type EnumTypeValue = string[] | number[] | Record<number, string>;

Expand Down
69 changes: 66 additions & 3 deletions packages/openapi-metadata/test/decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import {
ApiHeader,
ApiOperation,
ApiParam,
ApiProperty,
ApiQuery,
ApiResponse,
ApiSecurity,
ApiTags,
} from "../src/decorators";
} from "../src/decorators/index.js";
import {
ExcludeMetadataStorage,
ExtraModelsMetadataStorage,
Expand All @@ -21,8 +22,9 @@ import {
OperationParameterMetadataStorage,
OperationResponseMetadataStorage,
OperationSecurityMetadataStorage,
} from "../src/metadata";
import { ApiBasicAuth, ApiBearerAuth, ApiCookieAuth, ApiOauth2 } from "../src/decorators/api-security";
PropertyMetadataStorage,
} from "../src/metadata/index.js";
import { ApiBasicAuth, ApiBearerAuth, ApiCookieAuth, ApiOauth2 } from "../src/decorators/api-security.js";

test("@ApiOperation", () => {
class MyController {
Expand Down Expand Up @@ -189,3 +191,64 @@ test("@ApiExtraModels", () => {

expect(metadata).toEqual(["string"]);
});

test("@ApiProperty", () => {
class User {
@ApiProperty()
declare declared: string;

@ApiProperty()
// biome-ignore lint/style/noInferrableTypes: required for metadata
defined: number = 4;

@ApiProperty({ type: "string" })
explicitType = "test";

@ApiProperty({ example: "hey" })
get getter(): string {
return "hello";
}

@ApiProperty()
func(): boolean {
return false;
}
}

const metadata = PropertyMetadataStorage.getMetadata(User.prototype);

expect(metadata.declared).toMatchObject({
name: "declared",
required: true,
});
// @ts-expect-error
expect(metadata.declared?.type()).toEqual(String);

expect(metadata.defined).toMatchObject({
name: "defined",
required: true,
});
// @ts-expect-error
expect(metadata.defined?.type()).toEqual(Number);

expect(metadata.explicitType).toMatchObject({
name: "explicitType",
required: true,
type: "string",
});

expect(metadata.getter).toMatchObject({
name: "getter",
required: true,
example: "hey",
});
// @ts-expect-error
expect(metadata.getter?.type()).toEqual(String);

expect(metadata.func).toMatchObject({
name: "func",
required: true,
});
// @ts-expect-error
expect(metadata.func?.type()).toEqual(Boolean);
});
34 changes: 34 additions & 0 deletions packages/openapi-metadata/test/loaders/array.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Context } from "../../src/context.js";
import { ArrayTypeLoader } from "../../src/loaders/type.js";

let error: string | undefined = undefined;
const context: Context = {
schemas: {},
typeLoaders: [],
logger: {
warn: (message) => {
error = message;
},
},
};

test("simple array", async () => {
expect(await ArrayTypeLoader(context, [String])).toEqual({
type: "array",
items: {
type: "string",
},
});
});

test("empty array should warn", async () => {
// @ts-expect-error
expect(await ArrayTypeLoader(context, [])).toEqual(undefined);
expect(error).toContain("You tried to specify an array type without any item");
});

test("array with multiple items should warn", async () => {
// @ts-expect-error
expect(await ArrayTypeLoader(context, [String, Number])).toEqual(undefined);
expect(error).toContain("You tried to specify an array type with multiple items.");
});
25 changes: 25 additions & 0 deletions packages/openapi-metadata/test/loaders/class.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import "reflect-metadata";
import { ApiProperty } from "../../src/decorators/api-property.js";
import { ClassTypeLoader } from "../../src/loaders/type.js";
import type { Context } from "../../src/context.js";

test("simple class", async () => {
const context: Context = { schemas: {}, typeLoaders: [], logger: console };
class Post {
@ApiProperty()
declare id: string;
}

const result = await ClassTypeLoader(context, Post);

expect(result).toEqual({ $ref: "#/components/schemas/Post" });
expect(context.schemas.Post).toEqual({
type: "object",
properties: {
id: {
type: "string",
},
},
required: ["id"],
});
});
36 changes: 36 additions & 0 deletions packages/openapi-metadata/test/loaders/primitives.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { Context } from "../../src/context.js";
import { PrimitiveTypeLoader } from "../../src/loaders/type.js";

const context: Context = { schemas: {}, typeLoaders: [], logger: console };

test("string", async () => {
expect(await PrimitiveTypeLoader(context, "string")).toEqual({
type: "string",
});

expect(await PrimitiveTypeLoader(context, "number")).toEqual({
type: "number",
});

expect(await PrimitiveTypeLoader(context, "boolean")).toEqual({
type: "boolean",
});

expect(await PrimitiveTypeLoader(context, "integer")).toEqual({
type: "integer",
});
});

test("constructor", async () => {
expect(await PrimitiveTypeLoader(context, String)).toEqual({
type: "string",
});

expect(await PrimitiveTypeLoader(context, Number)).toEqual({
type: "number",
});

expect(await PrimitiveTypeLoader(context, Boolean)).toEqual({
type: "boolean",
});
});