Skip to content

Commit

Permalink
✨ feat: support OpenAPI request mode
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Dec 11, 2023
1 parent 916fe4e commit 605d947
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"scripts": {
"build": "father build",
"ci": "npm run lint && npm run type-check && npm run doctor",
"dev": "father dev",
"doctor": "father doctor",
"lint": "eslint \"{src,api,docs}/**/*.{js,jsx,ts,tsx}\" --fix",
"lint:md": "remark . --quiet --frail --output",
Expand Down Expand Up @@ -51,6 +50,7 @@
"dependencies": {
"@cfworker/json-schema": "^1",
"@lobehub/chat-plugin-sdk": "latest",
"swagger-client": "^3.24.5",
"zod": "^3"
},
"devDependencies": {
Expand Down
47 changes: 46 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,14 +176,59 @@ const createGateway = (pluginsIndexUrl: string = DEFAULT_PLUGINS_INDEX_URL) => {
});
}

// ========== 8. 发送请求 ========== //
// ========== 8. 兼容 OpenAPI 请求模式 ========== //
if (manifest.openapi) {
// @ts-ignore
const { default: SwaggerClient } = await import('swagger-client');

const client = await SwaggerClient({
authorizations: {
// apiKeyAuth: '',
},
url: manifest.openapi,
});

const parameters = JSON.parse(args || '{}');

try {
const res = await client.execute({
operationId: apiName,
parameters,
});

return new Response(res.text);
} catch (error) {
// 如果没有 status,说明没有发送请求,可能是 openapi 相关调用实现的问题
if (!(error as any).status)
return createErrorResponse('PluginGatewayError', {
api,
error: (error as Error).message,
message:
'[plugin] there are problem with sending openapi request, please contact with LobeHub Team',
});

// 如果是 401 则说明是鉴权问题
if ((error as Response).status === 401)
return createErrorResponse(PluginErrorType.PluginSettingsInvalid);

return createErrorResponse(PluginErrorType.PluginServerError, { error });
}
}

if (!api.url)
return createErrorResponse(PluginErrorType.PluginApiParamsError, {
api,
message: '[plugin] missing api url',
});

const response = await fetch(api.url, {
body: args,
headers: createHeadersWithPluginSettings(settings),
method: 'POST',
});

// ========== 9. 发送请求 ========== //

// 不正常的错误,直接返回请求
if (!response.ok) return response;

Expand Down

0 comments on commit 605d947

Please sign in to comment.