Skip to content

Commit

Permalink
fix(schema): fix Default decorator signature
Browse files Browse the repository at this point in the history
Closes: #2968
  • Loading branch information
Romakita committed Feb 6, 2025
1 parent 8580b1a commit 81b42b6
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
6 changes: 5 additions & 1 deletion packages/specs/schema/src/components/default/schemaMapper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {getValue, isObject} from "@tsed/core";
import {getValue, isFunction, isObject} from "@tsed/core";

import {mapAliasedProperties} from "../../domain/JsonAliasMap.js";
import {JsonSchema} from "../../domain/JsonSchema.js";
Expand Down Expand Up @@ -127,6 +127,10 @@ function serializeSchema(schema: JsonSchema, options: JsonSchemaOptions) {
};
}

if (isFunction(obj.default)) {
obj.default = obj.default();
}

obj = execMapper("required", [obj, schema], options);
obj = execMapper("nullable", [obj, schema], options);
obj = alterOneOf(obj, schema, options);
Expand Down
20 changes: 20 additions & 0 deletions packages/specs/schema/src/decorators/common/default.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,24 @@ describe("@Default", () => {
type: "object"
});
});
it("should declare prop (Date.now)", () => {
// WHEN
class Model {
@Default(Date.now)
num: Date = new Date();

constructor() {}
}

// THEN
expect(getJsonSchema(Model)).toEqual({
properties: {
num: {
default: expect.any(Number),
type: "string"
}
},
type: "object"
});
});
});
2 changes: 1 addition & 1 deletion packages/specs/schema/src/decorators/common/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {JsonEntityFn} from "./jsonEntityFn.js";
* @schema
* @input
*/
export function Default(defaultValue: JSONSchema6Type | undefined) {
export function Default(defaultValue: JSONSchema6Type | undefined | (() => JSONSchema6Type)) {
return JsonEntityFn((store) => {
store.itemSchema.default(defaultValue);
});
Expand Down
2 changes: 1 addition & 1 deletion packages/specs/schema/src/domain/JsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ export class JsonSchema extends Map<string, any> implements NestedGenerics {
* It is RECOMMENDED that a default value be valid against the associated schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3
*/
default(value: JSONSchema6Type | undefined) {
default(value: JSONSchema6Type | undefined | (() => JSONSchema6Type)) {
super.set("default", value);

return this;
Expand Down

0 comments on commit 81b42b6

Please # to comment.