Skip to content

Commit

Permalink
feat(common): Add json schema const decorator.
Browse files Browse the repository at this point in the history
  • Loading branch information
boyko authored and Romakita committed Apr 23, 2020
1 parent 9412a62 commit 8ec59b3
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/common/src/jsonschema/decorators/const.spec.ts
@@ -0,0 +1,28 @@
import {Const, JsonSchema} from "../../../src/jsonschema";
import {stubSchemaDecorator} from "./utils";

describe("Const", () => {
describe("when const is a string", () => {
it("should store data", () => {
const decorateStub = stubSchemaDecorator();
const schema = new JsonSchema();
Const("0");
// @ts-ignore
decorateStub.getCall(0).args[0](schema);
schema.const.should.eq("0");
decorateStub.restore();
});
});

describe("when const is a boolean", () => {
it("should store data", () => {
const decorateStub = stubSchemaDecorator();
const schema = new JsonSchema();
Const(false);
// @ts-ignore
decorateStub.getCall(0).args[0](schema);
schema.const.should.eq(false);
decorateStub.restore();
});
});
});
66 changes: 66 additions & 0 deletions packages/common/src/jsonschema/decorators/const.ts
@@ -0,0 +1,66 @@
import {JSONSchema6Type} from "json-schema";
import {decoratorSchemaFactory} from "../utils/decoratorSchemaFactory";

/**
* The const keyword is used to restrict a value to a fixed value.
*
*
* ## Example
* ### With a string
*
* ```typescript
* class Model {
* @Const("value1")
* property: "value1";
* }
* ```
*
* Will produce:
*
* ```json
* {
* "type": "object",
* "properties": {
* "property": {
* "type": "string",
* "const": "value1"
* }
* }
* }
* ```
* * ### With a boolean
*
* ```typescript
* class Model {
* @Const(true)
* property: boolean;
* }
* ```
*
* Will produce:
*
* ```json
* {
* "type": "object",
* "properties": {
* "property": {
* "type": "boolean",
* "const": true
* }
* }
* }
* ```
*
* @param {string | number | boolean } constValue
* @returns {Function}
* @decorator
* @ajv
* @property
* @jsonschema
* @auto-map The data will be stored on the right place according to the type and collectionType (primitive or collection).
*/
export function Const(constValue: JSONSchema6Type | any) {
return decoratorSchemaFactory(schema => {
schema.mapper.const = constValue;
});
}
1 change: 1 addition & 0 deletions packages/common/src/jsonschema/decorators/index.ts
Expand Up @@ -26,3 +26,4 @@ export * from "./any";
export * from "./schema";
export * from "./title";
export * from "./ignoreProperty";
export * from "./const";

0 comments on commit 8ec59b3

Please sign in to comment.