File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ import { omit } from "../utils/object" ;
2+ import type { OpenApiDocument } from "@omer-x/openapi-types" ;
3+
4+ function countReferences ( schemaName : string , source : string ) {
5+ return ( source . match ( new RegExp ( `"#/components/schemas/${ schemaName } "` , "g" ) ) ?? [ ] ) . length ;
6+ }
7+
8+ export default function clearUnusedSchemas ( {
9+ paths,
10+ components,
11+ } : Required < Pick < OpenApiDocument , "paths" | "components" > > ) {
12+ if ( ! components . schemas ) return { paths, components } ;
13+ const stringifiedPaths = JSON . stringify ( paths ) ;
14+ const stringifiedSchemas = Object . fromEntries ( Object . entries ( components . schemas ) . map ( ( [ schemaName , schema ] ) => {
15+ return [ schemaName , JSON . stringify ( schema ) ] ;
16+ } ) ) ;
17+ return {
18+ paths,
19+ components : {
20+ schemas : Object . fromEntries ( Object . entries ( components . schemas ) . filter ( ( [ schemaName ] ) => {
21+ const otherSchemas = omit ( stringifiedSchemas , schemaName ) ;
22+ return (
23+ countReferences ( schemaName , stringifiedPaths ) > 0 ||
24+ countReferences ( schemaName , Object . values ( otherSchemas ) . join ( "" ) ) > 0
25+ ) ;
26+ } ) ) ,
27+ } ,
28+ } ;
29+ }
Original file line number Diff line number Diff line change 1+ /* export function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
2+ return Object.fromEntries(Object.entries(object).filter(([key]) => keys.includes(key as K))) as Pick<T, K>;
3+ } */
4+
5+ export function omit < T extends object , K extends keyof T > ( object : T , ...keys : K [ ] ) {
6+ return Object . fromEntries ( Object . entries ( object ) . filter ( ( [ key ] ) => ! keys . includes ( key as K ) ) ) as Omit < T , K > ;
7+ }
8+
9+ /* export function pluck<T, K extends keyof T>(collection: T[], key: K) {
10+ return collection.map(item => item[key]) as T[K][];
11+ } */
You can’t perform that action at this time.
0 commit comments