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: add http channel support #176

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
3 changes: 3 additions & 0 deletions docs/inputs/asyncapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ To customize the code generation through the AsyncAPI document, use the `x-the-c
}
```

### HTTP


## FAQ

### How does it relate to AsyncAPI Generator and templates?
Expand Down
44 changes: 44 additions & 0 deletions docs/protocols/http.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
sidebar_position: 99
---

# HTTP(S)

Both client and server generator is available.

It is currently available through the generators ([channels](../generators/channels.md)):

All of this is available through [AsyncAPI](../inputs/asyncapi.md).

## TypeScript

## Server features

| **Feature** | Client | Server |
|---|---|---|
| Download | ➗ | ➗ |
| Upload | ➗ | ➗ |
| Offset based Pagination | ➗ | ➗ |
| Cursor based Pagination | ➗ | ➗ |
| Page based Pagination | ➗ | ➗ |
| Time based Pagination | ➗ | ➗ |
| Keyset based Pagination | ➗ | ➗ |
| Retry with backoff | ➗ | ➗ |
| OAuth2 Authorization code | ➗ | ➗ |
| OAuth2 Implicit | ➗ | ➗ |
| OAuth2 password | ➗ | ➗ |
| OAuth2 Client Credentials | ➗ | ➗ |
| Username/password Authentication | ➗ | ➗ |
| Bearer Authentication | ➗ | ➗ |
| Basic Authentication | ➗ | ➗ |
| API Key Authentication | ➗ | ➗ |
| JSON Based API | ➗ | ➗ |
| POST | ➗ | ➗ |
| GET | ➗ | ➗ |
| PATCH | ➗ | ➗ |
| DELETE | ➗ | ➗ |
| PUT | ➗ | ➗ |
| HEAD | ➗ | ➗ |
| OPTIONS | ➗ | ➗ |
| TRACE | ➗ | ➗ |
| CONNECT | ➗ | ➗ |
3 changes: 3 additions & 0 deletions src/codegen/generators/helpers/payloads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export async function generateAsyncAPIPayloads<GeneratorType>(
schemaObj.oneOf = [];
schemaObj['$id'] = pascalCase(`${preId}_Payload`);
for (const message of messages) {
if (message.hasPayload()) {
break;
}
const schema = AsyncAPIInputProcessor.convertToInternalSchema(
message.payload() as any
);
Expand Down
102 changes: 93 additions & 9 deletions src/codegen/generators/typescript/channels/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
addPayloadsToDependencies,
getMessageTypeAndModule
} from './utils';
import { renderHttpClient } from './protocols/http';
export {
renderedFunctionType,
TypeScriptChannelRenderType,
Expand Down Expand Up @@ -360,7 +361,7 @@ export async function generateTypeScriptChannels(
messageType: value.messageType,
replyType: value.replyType,
parameterType: parameter?.model?.type
} as renderedFunctionType;
};
})
);
const renderedDependencies = renders
Expand Down Expand Up @@ -475,7 +476,7 @@ export async function generateTypeScriptChannels(
}
case 'mqtt': {
const topic = simpleContext.topic;
let natsContext: RenderRegularParameters = {
let mqttContext: RenderRegularParameters = {
...simpleContext,
topic,
messageType: ''
Expand All @@ -493,13 +494,12 @@ export async function generateTypeScriptChannels(
}
const {messageModule, messageType} =
getMessageTypeAndModule(payload);
natsContext = {
...natsContext,
mqttContext = {
...mqttContext,
messageType,
messageModule,
subName: findNameFromOperation(operation, channel)
};

const action = operation.action();
if (
shouldRenderFunctionType(
Expand All @@ -509,7 +509,7 @@ export async function generateTypeScriptChannels(
generator.asyncapiReverseOperations
)
) {
renders.push(MqttRenderer.renderPublish(natsContext));
renders.push(MqttRenderer.renderPublish(mqttContext));
}
}
} else {
Expand All @@ -521,7 +521,7 @@ export async function generateTypeScriptChannels(
}
const {messageModule, messageType} =
getMessageTypeAndModule(payload);
natsContext = {...natsContext, messageType, messageModule};
mqttContext = {...mqttContext, messageType, messageModule};
if (
shouldRenderFunctionType(
functionTypeMapping,
Expand All @@ -530,9 +530,10 @@ export async function generateTypeScriptChannels(
generator.asyncapiReverseOperations
)
) {
renders.push(MqttRenderer.renderPublish(natsContext));
renders.push(MqttRenderer.renderPublish(mqttContext));
}
}

protocolCodeFunctions[protocol].push(
...renders.map((value) => value.code)
);
Expand All @@ -553,7 +554,91 @@ export async function generateTypeScriptChannels(
dependencies.push(...(new Set(renderedDependencies) as any));
break;
}

case 'http_client': {
const topic = simpleContext.topic;
const renders = [];
const operations = channel.operations().all();
if (operations.length > 0 && !ignoreOperation) {
for (const operation of operations) {
const payloadId = findOperationId(operation, channel);
const payload = payloads.operationModels[payloadId];
if (payload === undefined) {
throw new Error(
`Could not find payload for ${payloadId} for channel typescript generator ${JSON.stringify(payloads.operationModels, null, 4)}`
);
}
const {messageModule, messageType} =
getMessageTypeAndModule(payload);
const statusCodes = operation.messages().all().filter((value) => {
const statusCode = Number(value.bindings().get('http')?.json()['statusCode']);
return statusCode < 200 && statusCode > 300;
}).map((value) => {
const statusCode = Number(value.bindings().get('http')?.json()['statusCode']);
return {
code: statusCode, description: value.description() ?? 'Unknown'
};
});
const reply = operation.reply();
if (reply) {
const replyId = findReplyId(operation, reply, channel);
const replyMessageModel = payloads.operationModels[replyId];
if (!replyMessageModel) {
continue;
}
const {
messageModule: replyMessageModule,
messageType: replyMessageType
} = getMessageTypeAndModule(replyMessageModel);
const shouldRenderRequest = shouldRenderFunctionType(
functionTypeMapping,
ChannelFunctionTypes.HTTP_CLIENT,
operation.action(),
generator.asyncapiReverseOperations
);
if (shouldRenderRequest) {
const httpMethod = operation.bindings().get('http')?.json()['method'] ?? 'GET';
renders.push(
renderHttpClient({
subName: findNameFromOperation(operation, channel),
requestMessageModule: messageModule,
requestMessageType: messageType,
replyMessageModule,
replyMessageType,
requestTopic: topic,
method: httpMethod.toUpperCase(),
statusCodes,
channelParameters:
parameter !== undefined
? (parameter.model as any)
: undefined
})
);
}
}
}
}
protocolCodeFunctions[protocol].push(
...renders.map((value) => value.code)
);

externalProtocolFunctionInformation[protocol].push(
...renders.map((value) => {
return {
functionType: value.functionType,
functionName: value.functionName,
messageType: value.messageType,
replyType: value.replyType,
parameterType: parameter?.model?.type
};
})
);
const renderedDependencies = renders
.map((value) => value.dependencies)
.flat(Infinity);
dependencies.push(...(new Set(renderedDependencies) as any));
break;
}
case 'amqp': {
const topic = simpleContext.topic;
let amqpContext: RenderRegularParameters = {
Expand Down Expand Up @@ -649,7 +734,6 @@ export async function generateTypeScriptChannels(
protocolCodeFunctions[protocol].push(
...renders.map((value) => value.code)
);

externalProtocolFunctionInformation[protocol].push(
...renders.map((value) => {
return {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export function renderCommonHttpCode() {
return `type RequestCredentials = "omit" | "include" | "same-origin";
export type Json = any;
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
export type HTTPHeaders = { [key: string]: string };
export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
export type HTTPBody = Json | URLSearchParams;
export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody };

export interface FetchCallbackResponse {
ok: boolean,
status: number,
statusText: string,
json: () => Record<any, any> | Promise<Record<any, any>>,
}
export type FetchCallback = (url: string, options: HTTPRequestInit) => FetchCallbackResponse | Promise<FetchCallbackResponse>;

export interface RequestContext<RequestPayload> {
payload: RequestPayload,
basePath?: string; // override base path
server?: 'http://localhost:3000'
//username?: string; // parameter for basic security
//password?: string; // parameter for basic security
//apiKey?: string | ((name: string) => string | Promise<string>); // parameter for apiKey security
accessToken?: string | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
additionalHeaders?: HTTPHeaders; //header params we want to use on every request,
fetch?: FetchCallback
}
export interface InternalRequestContext<RequestPayload> {
payload: RequestPayload,
basePath: string; // override base path
server?: 'http://localhost:3000'
//username?: string; // parameter for basic security
//password?: string; // parameter for basic security
//apiKey?: string | ((name: string) => string | Promise<string>); // parameter for apiKey security
accessToken?: string | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
additionalHeaders?: HTTPHeaders; //header params we want to use on every request,
fetch: FetchCallback
}
export class FetchError extends Error {
override name = "FetchError";
code: number;
constructor(public cause: Error, code: number, msg: string) {
super(msg);
this.code = code;
}
}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { ConstrainedObjectModel } from "@asyncapi/modelina";
import { SingleFunctionRenderType } from "../../../../../types";
import { pascalCase } from "../../../utils";
import { ChannelFunctionTypes } from "../../types";

export interface RenderHttpParameters {
requestTopic: string;
requestMessageType: string;
requestMessageModule: string | undefined;
replyMessageType: string;
replyMessageModule: string | undefined;
channelParameters: ConstrainedObjectModel | undefined;
statusCodes?: {code: number, description:string}[]
subName?: string;
functionName?: string;
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
}

export function renderHttpClient({
requestTopic,
requestMessageType,
requestMessageModule,
replyMessageType,
replyMessageModule,
channelParameters,
method,
statusCodes = [],
subName = pascalCase(requestTopic),
functionName = `${method.toLowerCase()}${subName}`,
}: RenderHttpParameters): SingleFunctionRenderType {
const addressToUse = channelParameters
? `parameters.getChannelWithParameters('${requestTopic}')`
: `'${requestTopic}'`;
const messageType = requestMessageModule
? `${requestMessageModule}.${requestMessageType}`
: requestMessageType;
const replyType = replyMessageModule
? `${replyMessageModule}.${replyMessageType}`
: replyMessageType;
const statusCodeChecks = statusCodes.map((value) => {
return `else if (response.status === ${value.code}) {
return Promise.reject(new FetchError(new Error(response.statusText), response.status, '${value.description}'));
}`;
});
const code = `async ${functionName}(context: RequestContext<${messageType}>): Promise<${replyType}> {
const parsedContext: InternalRequestContext<${messageType}> = {
...{
fetch: async (url, options) => {
return NodeFetch.default(url, {
body: options.body,
method: options.method,
headers: options.headers
})
},
basePath: '${addressToUse}',
},
...context,
}
const headers: HTTPHeaders = {
'Content-Type': 'application/json',
...parsedContext.additionalHeaders
};
const url = parsedContext.server ?? parsedContext.basePath;

let body: any;
if (parsedContext.payload) {
body = parsedContext.payload.marshal();
}
if (parsedContext.accessToken) {
// oauth required
headers["Authorization"] = typeof parsedContext.accessToken === 'string' ? parsedContext.accessToken : await parsedContext.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}

const response = await parsedContext.fetch(url, {
method: ${method},
headers,
body,
credentials: parsedContext.credentials,
});
if (response.ok) {
const data = await response.json();
return ${replyType}.unmarshal(data);
} ${statusCodeChecks.join('\n ')}
return Promise.reject(new Error(response.statusText));
}`;
return {
messageType,
replyType,
code,
functionName,
dependencies: [`import { URLSearchParams } from 'url';`, `import * as NodeFetch from 'node-fetch'; `],
functionType: ChannelFunctionTypes.HTTP_CLIENT
};
}
Loading
Loading