feat: specify the api's auth type (#2715)

This commit is contained in:
Finley Ge
2024-09-15 13:06:51 +08:00
committed by GitHub
parent d0e8f7203c
commit 1ebc95a282
5 changed files with 103 additions and 25 deletions

View File

@@ -4,7 +4,7 @@ import * as path from 'path';
import { convertOpenApi } from './openapi';
const rootPath = 'projects/app/src/pages/api';
const exclude = ['/admin', '/proApi'];
const exclude = ['/admin', '/proApi', 'test.ts'];
function getAllFiles(dir: string) {
let files: string[] = [];
@@ -39,6 +39,22 @@ const openapi = convertOpenApi({
version: '1.0.0',
author: 'FastGPT'
},
components: {
securitySchemes: {
apiKey: {
type: 'apiKey',
name: 'Authorization',
in: 'header',
scheme: 'bearer'
},
token: {
type: 'apiKey',
in: 'token',
name: 'token',
scheme: 'basic'
}
}
},
servers: [
{
url: 'http://localhost:4000'

View File

@@ -29,10 +29,16 @@ type OpenAPIResponse = {
};
};
type OpenAPISecurity = {
apiKey?: string[];
token?: string[];
};
type PathType = {
[method: string]: {
description: string;
parameters: OpenAPIParameter[];
security?: OpenAPISecurity[];
responses: OpenAPIResponse;
};
};
@@ -52,6 +58,22 @@ type OpenApiType = {
servers?: {
url: string;
}[];
components: {
securitySchemes: {
apiKey: {
type: 'apiKey';
name: 'Authorization';
in: 'header';
scheme: 'bearer';
};
token: {
type: 'apiKey';
in: 'token';
name: 'token';
scheme: 'basic';
};
};
};
};
export function convertPath(api: ApiType): PathType {
@@ -97,6 +119,17 @@ export function convertPath(api: ApiType): PathType {
}
}
const security: OpenAPISecurity[] = [];
if (api.authorization === 'apikey') {
security.push({
apiKey: []
});
} else if (api.authorization === 'token') {
security.push({
token: []
});
}
const responses: OpenAPIResponse = (() => {
if (api.response) {
if (Array.isArray(api.response)) {
@@ -159,6 +192,7 @@ export function convertPath(api: ApiType): PathType {
return {
[method]: {
description: api.description ?? '',
security,
parameters,
responses
}

View File

@@ -6,6 +6,7 @@ export type ApiMetaData = {
export type ApiType = {
description?: string;
authorization?: 'apikey' | 'token';
path: string;
url: string;
query?: itemType | itemType[];

View File

@@ -213,7 +213,10 @@ function getMethod(api: ApiType): 'GET' | 'POST' {
export function parseAPI({ path, rootPath }: { path: string; rootPath: string }): ApiType {
const code = fs.readFileSync(path, 'utf-8');
const authApiKey = code.includes('authApiKey: true');
const authToken = code.includes('authToken: true');
const api = parseCode(code);
api.authorization = authApiKey ? 'apikey' : authToken ? 'token' : undefined;
api.url = path.replace('.ts', '').replace(rootPath, '');
api.path = path;
if (api.method === undefined) {