Skip to content

feat: Implement Async API and add @tsed/socketio-v2 #2441

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

Open
wants to merge 3 commits into
base: production
Choose a base branch
from
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
4 changes: 2 additions & 2 deletions packages/platform/platform-middlewares/src/decorators/use.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {DecoratorTypes, UnsupportedDecoratorType} from "@tsed/core";
import {JsonEntityFn, Route} from "@tsed/schema";
import {JsonEntityFn, Operation} from "@tsed/schema";

/**
* Mounts the specified middleware function or functions at the specified path: the middleware function is executed when
Expand All @@ -26,7 +26,7 @@ export function Use(...args: any[]): Function {
return JsonEntityFn((entity, parameters) => {
switch (entity.decoratorType) {
case DecoratorTypes.METHOD:
return Route(...args);
return Operation(...args);

case DecoratorTypes.CLASS:
entity.store.merge("middlewares", {
Expand Down
2 changes: 1 addition & 1 deletion packages/specs/schema/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
coverageThreshold: {
global: {
statements: 99.45,
branches: 96.18,
branches: 96.2,
functions: 100,
lines: 99.45
}
Expand Down
80 changes: 80 additions & 0 deletions packages/specs/schema/src/components/async-api/channelsMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import {camelCase} from "change-case";
import {OperationVerbs} from "../../constants/OperationVerbs";
import {JsonMethodStore} from "../../domain/JsonMethodStore";
import {JsonMethodPath} from "../../domain/JsonOperation";
import {JsonSchemaOptions} from "../../interfaces/JsonSchemaOptions";
import {execMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {buildPath} from "../../utils/buildPath";
import {getJsonEntityStore} from "../../utils/getJsonEntityStore";
import {getOperationsStores} from "../../utils/getOperationsStores";
import {removeHiddenOperation} from "../../utils/removeHiddenOperation";

const ALLOWED_VERBS = [OperationVerbs.PUBLISH, OperationVerbs.SUBSCRIBE];

function pushToChannels(options: JsonSchemaOptions) {
return (
channels: any,
{
operationPath,
operationStore
}: {
operationPath: JsonMethodPath;
operationStore: JsonMethodStore;
}
) => {
const path = options.ctrlRootPath || "/";
const method = operationPath.method.toLowerCase();
const operationId = camelCase(`${method.toLowerCase()} ${operationStore.parent.schema.getName()}`);

const message = execMapper("message", [operationStore, operationPath], options);

return {
...channels,
[path]: {
...(channels as any)[path],
[method]: {
...(channels as any)[path]?.[method],
operationId,
message: {
oneOf: [...((channels as any)[path]?.[method]?.message?.oneOf || []), message]
}
}
}
};
};
}

function expandOperationPaths(options: JsonSchemaOptions) {
return (operationStore: JsonMethodStore) => {
const operationPaths = operationStore.operation.getAllowedOperationPath(ALLOWED_VERBS);

if (operationPaths.length === 0) {
return [];
}

return operationPaths.map((operationPath) => {
return {
operationPath,
operationStore
};
});
};
}

export function channelsMapper(model: any, {channels, rootPath, ...options}: JsonSchemaOptions) {
const store = getJsonEntityStore(model);
const ctrlPath = store.path;
const ctrlRootPath = buildPath(rootPath + ctrlPath);

options = {
...options,
ctrlRootPath
};

return [...getOperationsStores(model).values()]
.filter(removeHiddenOperation)
.flatMap(expandOperationPaths(options))
.reduce(pushToChannels(options), channels);
}

registerJsonSchemaMapper("channels", channelsMapper);
23 changes: 23 additions & 0 deletions packages/specs/schema/src/components/async-api/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {getValue, Type, uniqBy} from "@tsed/core";
import {SpecTypes} from "../../domain/SpecTypes";
import {execMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {SpecSerializerOptions} from "../../utils/getSpec";

function generate(model: Type<any>, options: SpecSerializerOptions) {
const specJson: any = {
channels: execMapper("channels", [model], options)
};

specJson.tags = uniqBy(options.tags, "name");

if (options.components?.schemas && Object.keys(options.components.schemas).length) {
specJson.components = {
...options.components,
schemas: options.components.schemas
};
}

return specJson;
}

registerJsonSchemaMapper("generate", generate, SpecTypes.ASYNCAPI);
61 changes: 61 additions & 0 deletions packages/specs/schema/src/components/async-api/messageMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {cleanObject, getValue} from "@tsed/core";
import {OperationVerbs} from "../../constants/OperationVerbs";
import {JsonMethodStore} from "../../domain/JsonMethodStore";
import {JsonMethodPath} from "../../domain/JsonOperation";
import {SpecTypes} from "../../domain/SpecTypes";
import {JsonSchemaOptions} from "../../interfaces/JsonSchemaOptions";
import {execMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {makeOf} from "../../utils/somethingOf";

export function messageMapper(
jsonOperationStore: JsonMethodStore,
operationPath: JsonMethodPath,
{tags = [], defaultTags = [], ...options}: JsonSchemaOptions = {}
) {
const {path: event, method} = operationPath;

const messageKey = String(event);

let message: any = getValue(
options.components,
"messages." + event,
cleanObject({
description: jsonOperationStore.operation.get("description"),
summary: jsonOperationStore.operation.get("summary")
})
);

if (method.toUpperCase() === OperationVerbs.PUBLISH) {
const payload = execMapper("payload", [jsonOperationStore, operationPath], options);

if (payload) {
message.payload = payload;
}

const responses = jsonOperationStore.operation
.getAllowedOperationPath([OperationVerbs.SUBSCRIBE])
.map((operationPath) => {
return execMapper("message", [jsonOperationStore, operationPath], options);
})
.filter(Boolean);

const responsesSchema = makeOf("oneOf", responses);

if (responsesSchema) {
message["x-response"] = responsesSchema;
}
} else {
const response = execMapper("response", [jsonOperationStore, operationPath], options);

if (response) {
message["x-response"] = response;
}
}

options.components!.messages = options.components!.messages || {};
options.components!.messages[messageKey] = message;

return {$ref: `#/components/messages/${messageKey}`};
}

registerJsonSchemaMapper("message", messageMapper, SpecTypes.ASYNCAPI);
60 changes: 60 additions & 0 deletions packages/specs/schema/src/components/async-api/payloadMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {setValue} from "@tsed/core";
import {pascalCase} from "change-case";
import {JsonMethodStore} from "../../domain/JsonMethodStore";
import {JsonMethodPath, JsonOperation} from "../../domain/JsonOperation";
import {JsonParameter} from "../../domain/JsonParameter";
import {isParameterType, JsonParameterTypes} from "../../domain/JsonParameterTypes";
import {SpecTypes} from "../../domain/SpecTypes";
import {JsonSchemaOptions} from "../../interfaces/JsonSchemaOptions";
import {execMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {popGenerics} from "../../utils/generics";
import {makeOf} from "../../utils/somethingOf";

function mapOptions(parameter: JsonParameter, options: JsonSchemaOptions = {}) {
return {
...options,
groups: parameter.groups,
groupsName: parameter.groupsName
};
}

function getParameters(jsonOperation: JsonOperation, options: JsonSchemaOptions): JsonParameter[] {
return jsonOperation.get("parameters").filter((parameter: JsonParameter) => isParameterType(parameter.get("in")));
}

export function payloadMapper(jsonOperationStore: JsonMethodStore, operationPath: JsonMethodPath, options: JsonSchemaOptions) {
const parameters = getParameters(jsonOperationStore.operation, options);
const payloadName = pascalCase([operationPath.path, operationPath.method, "Payload"].join(" "));

setValue(options, `components.schemas.${payloadName}`, {});

const allOf = parameters
.map((parameter) => {
const opts = mapOptions(parameter, options);
const jsonSchema = execMapper("item", [parameter.$schema], {
...opts,
...popGenerics(parameter)
});

switch (parameter.get("in")) {
case JsonParameterTypes.BODY:
return jsonSchema;
case JsonParameterTypes.QUERY:
case JsonParameterTypes.PATH:
case JsonParameterTypes.HEADER:
return {
type: "object",
properties: {
[parameter.get("name")]: jsonSchema
}
};
}

return jsonSchema;
}, {})
.filter(Boolean);

return makeOf("allOf", allOf);
}

registerJsonSchemaMapper("payload", payloadMapper, SpecTypes.ASYNCAPI);
69 changes: 69 additions & 0 deletions packages/specs/schema/src/components/async-api/responseMapper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {setValue} from "@tsed/core";
import {pascalCase} from "change-case";
import {JsonMethodStore} from "../../domain/JsonMethodStore";
import {JsonMethodPath} from "../../domain/JsonOperation";
import {SpecTypes} from "../../domain/SpecTypes";
import {JsonSchemaOptions} from "../../interfaces/JsonSchemaOptions";
import {execMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {makeOf} from "../../utils/somethingOf";

export function responsePayloadMapper(jsonOperationStore: JsonMethodStore, operationPath: JsonMethodPath, options: JsonSchemaOptions) {
const responses = jsonOperationStore.operation.getResponses();
const statuses: number[] = [];
const statusesTexts: string[] = [];
const successSchemes: unknown[] = [];
const errorSchemes: unknown[] = [];

[...responses.entries()].forEach(([status, jsonResponse]) => {
const response = execMapper("map", [jsonResponse], options);

statuses.push(+status);

statusesTexts.push(response.description);

if (+status !== 204) {
const {content} = response;
const schema = content[Object.keys(content)[0]];

if (+status >= 200 && +status < 400) {
successSchemes.push(schema);
} else {
successSchemes.push(schema);
}
}
});

const responsePayloadName = pascalCase([operationPath.path, operationPath.method, "Response"].join(" "));
const responsePayload = {
type: "object",
properties: {
status: {
type: "number",
enum: statuses
},
statusText: {
type: "string",
enum: statusesTexts
}
},
required: ["status"]
};

const dataSchema = makeOf("oneOf", successSchemes);

if (dataSchema) {
setValue(responsePayload, "properties.data", dataSchema);
}

const errorSchema = makeOf("oneOf", errorSchemes);

if (errorSchemes.length) {
setValue(responsePayload, "properties.error", errorSchema);
}

setValue(options, `components.schemas.${responsePayloadName}`, responsePayload);

return {$ref: `#/components/schemas/${responsePayloadName}`};
}

registerJsonSchemaMapper("response", responsePayloadMapper, SpecTypes.ASYNCAPI);
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import {JsonLazyRef} from "../domain/JsonLazyRef";
import {JsonSchema} from "../domain/JsonSchema";
import {JsonSchemaOptions} from "../interfaces/JsonSchemaOptions";
import {execMapper, oneOfMapper, registerJsonSchemaMapper} from "../registries/JsonSchemaMapperContainer";
import {mapGenericsOptions} from "../utils/generics";
import {toRef} from "../utils/ref";
import {JsonLazyRef} from "../../domain/JsonLazyRef";
import {JsonSchema} from "../../domain/JsonSchema";
import {JsonSchemaOptions} from "../../interfaces/JsonSchemaOptions";
import {execMapper, oneOfMapper, registerJsonSchemaMapper} from "../../registries/JsonSchemaMapperContainer";
import {mapGenericsOptions} from "../../utils/generics";
import {toRef} from "../../utils/ref";

export function anyMapper(input: any, options: JsonSchemaOptions = {}): any {
if (typeof input !== "object" || input === null) {
return input;
}

if (input instanceof JsonLazyRef) {
return execMapper("lazyRef", input, options);
return execMapper("lazyRef", [input], options);
}

if (input instanceof JsonSchema && input.get("enum") instanceof JsonSchema) {
Expand All @@ -21,13 +21,13 @@ export function anyMapper(input: any, options: JsonSchemaOptions = {}): any {
}

if (input.$kind && input.$isJsonDocument) {
const kind = oneOfMapper(input.$kind, "map");
const schema = execMapper(kind, input, mapGenericsOptions(options));
const kind = oneOfMapper([input.$kind, "map"], options);
const schema = execMapper(kind, [input], mapGenericsOptions(options));

return input.canRef ? toRef(input, schema, options) : schema;
}

return execMapper("object", input, options);
return execMapper("object", [input], options);
}

registerJsonSchemaMapper("any", anyMapper);
Loading