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 schema update async api #2488

Merged
merged 4 commits into from
Nov 28, 2023
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
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
66 changes: 38 additions & 28 deletions packages/platform/platform-router/src/domain/PlatformRouters.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import {getValue, Hooks, Type} from "@tsed/core";
import {ControllerProvider, GlobalProviders, Injectable, InjectorService, Provider, ProviderType, TokenProvider} from "@tsed/di";
import {PlatformParamsCallback} from "@tsed/platform-params";
import {concatPath, getOperationsRoutes, JsonMethodStore} from "@tsed/schema";
import {useContextHandler} from "../utils/useContextHandler";
import {PlatformHandlerMetadata} from "./PlatformHandlerMetadata";
import {PlatformLayer} from "./PlatformLayer";
import {PlatformRouter} from "./PlatformRouter";
import { getValue, Hooks, Type } from "@tsed/core";
import {
ControllerProvider,
GlobalProviders,
Injectable,
InjectorService,
Provider,
ProviderType,
TokenProvider
} from "@tsed/di";
import { PlatformParamsCallback } from "@tsed/platform-params";
import { concatPath, getOperationsRoutes, JsonMethodStore, OPERATION_HTTP_VERBS } from "@tsed/schema";
import { useContextHandler } from "../utils/useContextHandler";
import { PlatformHandlerMetadata } from "./PlatformHandlerMetadata";
import { PlatformLayer } from "./PlatformLayer";
import { PlatformRouter } from "./PlatformRouter";

let AUTO_INC = 0;

Expand Down Expand Up @@ -35,7 +43,7 @@ function createInjectableRouter(injector: InjectorService, provider: ControllerP
}

GlobalProviders.createRegistry(ProviderType.CONTROLLER, ControllerProvider, {
onInvoke(provider: ControllerProvider, locals: any, {injector}) {
onInvoke(provider: ControllerProvider, locals: any, { injector }) {
const router = createInjectableRouter(injector, provider);
locals.set(PlatformRouter, router);
}
Expand All @@ -50,30 +58,19 @@ export interface AlterEndpointHandlersArg {
@Injectable()
export class PlatformRouters {
readonly hooks = new Hooks();
readonly allowedVerbs = OPERATION_HTTP_VERBS;

constructor(protected readonly injector: InjectorService) {}
constructor(protected readonly injector: InjectorService) {
}

prebuild() {
this.injector.getProviders(ProviderType.CONTROLLER).forEach((provider: ControllerProvider) => {
createInjectableRouter(this.injector, provider);
});
}

private sortHandlers(handlers: AlterEndpointHandlersArg) {
const get = (token: TokenProvider) => {
return this.injector.getProvider(token)?.priority || 0;
};

const sort = (p1: TokenProvider, p2: TokenProvider) => (get(p1) < get(p2) ? -1 : get(p1) > get(p2) ? 1 : 0);

handlers.before = handlers.before.sort(sort);
handlers.after = handlers.after.sort(sort);

return handlers;
}

from(token: TokenProvider, parentMiddlewares: any[] = []) {
const {injector} = this;
const { injector } = this;
const provider = injector.getProvider<ControllerProvider>(token)!;

if (!provider) {
Expand All @@ -88,11 +85,11 @@ export class PlatformRouters {

const useBefore = getValue(provider, "middlewares.useBefore", []);

const {children} = provider;
const { children } = provider;

getOperationsRoutes(provider.token).forEach((operationRoute) => {
const {endpoint} = operationRoute;
const {beforeMiddlewares, middlewares: mldwrs, afterMiddlewares} = endpoint;
getOperationsRoutes(provider.token, { allowedVerbs: this.allowedVerbs }).forEach((operationRoute) => {
const { endpoint } = operationRoute;
const { beforeMiddlewares, middlewares: mldwrs, afterMiddlewares } = endpoint;

const useBefore = getValue(provider, "middlewares.useBefore", []);
const use = getValue(provider, "middlewares.use", []);
Expand Down Expand Up @@ -139,6 +136,19 @@ export class PlatformRouters {
return this.flatMapLayers(router.layers);
}

private sortHandlers(handlers: AlterEndpointHandlersArg) {
const get = (token: TokenProvider) => {
return this.injector.getProvider(token)?.priority || 0;
};

const sort = (p1: TokenProvider, p2: TokenProvider) => (get(p1) < get(p2) ? -1 : get(p1) > get(p2) ? 1 : 0);

handlers.before = handlers.before.sort(sort);
handlers.after = handlers.after.sort(sort);

return handlers;
}

private flatMapLayers(layers: PlatformLayer[]): PlatformLayer[] {
return layers
.flatMap((layer) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {catchError} from "@tsed/core";
import {Controller, InjectorService} from "@tsed/di";
import {UseBefore} from "@tsed/platform-middlewares";
import {Context, PlatformParams} from "@tsed/platform-params";
import {Delete, Get, Head, Options, Patch, Post, Put} from "@tsed/schema";
import {Delete, Get, Head, Options, Patch, Post, Publish, Put, Subscribe} from "@tsed/schema";
import {PlatformRouter} from "../src/domain/PlatformRouter";
import {AlterEndpointHandlersArg, PlatformRouters} from "../src/domain/PlatformRouters";

Expand Down Expand Up @@ -35,11 +35,13 @@ class NestedController {
@UseBefore(function useBefore() {})
class MyController {
@Get("/")
@Publish("get.event")
get(@Context() $ctx: Context) {
return $ctx;
}

@Post("/")
@Subscribe("update.event")
post() {}

@Put("/:id")
Expand Down
4 changes: 2 additions & 2 deletions packages/specs/schema/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ module.exports = {
roots: ["<rootDir>/src", "<rootDir>/test"],
coverageThreshold: {
global: {
statements: 99.45,
statements: 99.41,
branches: 96.19,
functions: 100,
lines: 99.45
lines: 99.41
}
},
moduleNameMapper: {
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);
Loading
Loading