mirror of
https://github.com/fluxerapp/fluxer
synced 2026-10-18 13:35:42 +09:00
refactor(schema): simplify validation and OpenAPI generation (#2709)
This commit is contained in:
1 parent
4bc5593f9f
commit
de1fd95a99
510 files changed
+29494
-36131
No files matched your search
@@ -1,54 +1,31 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {visitOpenAPISchemaObjects} from '@fluxer/openapi/src/OpenAPISchemaVisitor';
|
||||
import type {OpenAPIPathItem, OpenAPISchema} from '@fluxer/openapi/src/OpenAPITypes';
|
||||
|
||||
const OPENAPI_SCHEMA_REF_PATTERN = /#\/components\/schemas\/([A-Za-z0-9_]+)/;
|
||||
const SCHEMA_REFERENCE_PREFIX = '#/components/schemas/';
|
||||
|
||||
export function collectReferencedSchemaNames(
|
||||
paths: Record<string, OpenAPIPathItem>,
|
||||
allSchemas: Record<string, OpenAPISchema>,
|
||||
): Set<string> {
|
||||
const referenced = new Set<string>();
|
||||
function addSchema(schemaName: string): void {
|
||||
if (referenced.has(schemaName)) {
|
||||
return;
|
||||
}
|
||||
referenced.add(schemaName);
|
||||
if (allSchemas[schemaName]) {
|
||||
extractRefs(allSchemas[schemaName]);
|
||||
}
|
||||
}
|
||||
function extractRefs(value: unknown): void {
|
||||
if (value == null || typeof value !== 'object') {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
'$ref' in value &&
|
||||
typeof (
|
||||
value as {
|
||||
$ref: string;
|
||||
const pending: Array<unknown> = [{paths}];
|
||||
while (pending.length > 0) {
|
||||
const value = pending.pop();
|
||||
visitOpenAPISchemaObjects(value, (schema) => {
|
||||
if (!schema.$ref?.startsWith(SCHEMA_REFERENCE_PREFIX)) return;
|
||||
const schemaName = decodeURIComponent(schema.$ref.slice(SCHEMA_REFERENCE_PREFIX.length).split('/')[0])
|
||||
.replaceAll('~1', '/')
|
||||
.replaceAll('~0', '~');
|
||||
if (!referenced.has(schemaName)) {
|
||||
if (!Object.hasOwn(allSchemas, schemaName)) {
|
||||
throw new Error(`Reference to an unregistered OpenAPI schema: ${schema.$ref}`);
|
||||
}
|
||||
).$ref === 'string'
|
||||
) {
|
||||
const ref = (
|
||||
value as {
|
||||
$ref: string;
|
||||
}
|
||||
).$ref;
|
||||
const match = ref.match(OPENAPI_SCHEMA_REF_PATTERN);
|
||||
if (match) {
|
||||
addSchema(match[1]);
|
||||
referenced.add(schemaName);
|
||||
pending.push(allSchemas[schemaName]);
|
||||
}
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
extractRefs(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const nested of Object.values(value as Record<string, unknown>)) {
|
||||
extractRefs(nested);
|
||||
}
|
||||
});
|
||||
}
|
||||
extractRefs(paths);
|
||||
addSchema('Error');
|
||||
return referenced;
|
||||
}
|
||||
Reference in new issue
Block a user