Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
pyramation committed May 25, 2024
1 parent fddbc20 commit 347ddfa
Show file tree
Hide file tree
Showing 15 changed files with 91 additions and 133 deletions.
1 change: 1 addition & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"quote-props": ["error", "as-needed"],
"semi": ["error", "always"],
"simple-import-sort/imports": 1,
"simple-import-sort/exports": 1,
"unused-imports/no-unused-imports": 1,
Expand Down
6 changes: 3 additions & 3 deletions packages/schema-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ npm install schema-sdk

## Usage

Below are examples demonstrating how to use schema-sdk for generating TypeScript clients and handling OpenAPI specifications:
Below are examples demonstrating how to use `schema-sdk` for generating TypeScript clients and handling OpenAPI specifications:

### Generating OpenAPI Client

```ts
import schema from 'path-to-your/swagger.json';
import { generateOpenApiClient, getDefaultSchemaTSOptions } from 'schema-sdk';
import { generateOpenApiClient, getDefaultSchemaSDKOptions } from 'schema-sdk';
import { writeFileSync } from 'fs';

const options = getDefaultSchemaTSOptions({
const options = getDefaultSchemaSDKOptions({
exclude: [
'*.v1beta1.*',
'*.v2beta1.*',
Expand Down
6 changes: 3 additions & 3 deletions packages/schema-sdk/__tests__/openapi.generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ it('swagger', () => {
'io.k8s.api.events.v1.Event',
'io.k8s.api.flowcontrol*'
]
})
});
const code = generateOpenApiClient({
...options,
// version: 'v1',
Expand Down Expand Up @@ -64,7 +64,7 @@ it('merged', () => {
namingStrategy: {
useLastSegment: true
}
})
});
const code = generateOpenApiClient({
...options,
version: 'v1',
Expand All @@ -75,6 +75,6 @@ it('merged', () => {
});

it('openapi', () => {
const data = Object.keys(schema.definitions)
const data = Object.keys(schema.definitions);
writeFileSync(__dirname + '/../../../__fixtures__/output/swagger-definitions.json', JSON.stringify(data, null, 2));
});
9 changes: 4 additions & 5 deletions packages/schema-sdk/__tests__/template.literal.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import generate from '@babel/generator';
import { getDefaultSchemaTSOptions } from 'schema-typescript';

import { createPathTemplateLiteral } from '../src';
import { createPathTemplateLiteral, getDefaultSchemaSDKOptions } from '../src';

const options = getDefaultSchemaTSOptions();
const options = getDefaultSchemaSDKOptions();
export const renderTemplateTag = (str: string) => {
return generate(createPathTemplateLiteral({
...options,
mergedParams: true
}, str)).code
}
}, str)).code;
};
it('/osmosis/{gamm}/v1beta1/estimate/swap_exact_amount_in', () => {
expect(renderTemplateTag('/osmosis/{gamm}/v1beta1/estimate/swap_exact_amount_in'))
.toEqual('`/osmosis/${params.gamm}/v1beta1/estimate/swap_exact_amount_in`');
Expand Down
3 changes: 2 additions & 1 deletion packages/schema-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"dependencies": {
"@babel/generator": "^7.24.4",
"@babel/types": "^7.24.0",
"schema-typescript": "^0.5.0"
"schema-typescript": "^0.5.0",
"deepmerge": "^4.3.1"
},
"keywords": ["jsonschema", "schema", "typescript", "swagger", "openapi"]
}
7 changes: 2 additions & 5 deletions packages/schema-sdk/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { getDefaultSchemaTSOptions } from 'schema-typescript';

export * from './openapi';
export * from './openapi.types';
export * from './utils';

export { getDefaultSchemaTSOptions };
export * from './types';
export * from './utils';
52 changes: 18 additions & 34 deletions packages/schema-sdk/src/openapi.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,12 @@
import generate from '@babel/generator';
import * as t from '@babel/types';
import { SchemaTSOptions } from 'schema-typescript';
import { generateTypeScriptTypes } from 'schema-typescript';
import { getTypeNameSafe, shouldInclude, toCamelCase, toPascalCase } from 'schema-typescript';

import { OpenAPIPathItem, OpenAPISpec, Operation, Parameter, Response } from './openapi.types';
import { OpenAPIOptions } from './types';
import { createPathTemplateLiteral } from './utils';

export interface OpenAPIOptions extends SchemaTSOptions {
version?: 'v1' | 'v1beta1' | 'v2beta1' | 'v2beta2';
mergedParams?: boolean;
paths?: {
// Include/Exclude types
include?: string[];
exclude?: string[];

includeTags?: string[];
excludeTags?: string[];

includeRequests?: string[];
excludeRequests?: string[];
}
}

/**
includes: {
requests: ['patch', 'head', 'options', 'get', 'delete'],
Expand Down Expand Up @@ -86,11 +70,11 @@ const shouldIncludeOperation = (
const shouldIncludeByRequest = shouldInclude(method, {
include: options.paths?.includeRequests ?? [],
exclude: options.paths?.excludeRequests ?? []
})
});

if (!shouldIncludeByRequest) return false;
return true;
}
};

export const getApiTypeNameSafe = (options: OpenAPIOptions, str: string): string => {
return getTypeNameSafe(options.namingStrategy, str);
Expand Down Expand Up @@ -135,14 +119,14 @@ export const getResponseType = (options: OpenAPIOptions, prop: Response) => {
// resolve $ref
if (prop.schema) {
if (!prop.schema.$ref) {
throw new Error('no property set on open api parameter schema!')
throw new Error('no property set on open api parameter schema!');
}
const ref = prop.schema.$ref.split('/');
const definitionName = ref.pop();
return t.tsTypeReference(t.identifier(getApiTypeNameSafe(options, definitionName)));
}
return t.tsAnyKeyword();
}
};

export const getParameterType = (options: OpenAPIOptions, prop: Parameter) => {
if (prop.type) {
Expand All @@ -168,14 +152,14 @@ export const getParameterType = (options: OpenAPIOptions, prop: Parameter) => {
// resolve $ref
if (prop.schema) {
if (!prop.schema.$ref) {
throw new Error('no property set on open api parameter schema!')
throw new Error('no property set on open api parameter schema!');
}
const ref = prop.schema.$ref.split('/');
const definitionName = ref.pop();
return t.tsTypeReference(t.identifier(getApiTypeNameSafe(options, definitionName)));
}
return t.tsAnyKeyword();
}
};

interface ParameterInterfaces {
query: Parameter[];
Expand Down Expand Up @@ -203,8 +187,8 @@ const initParams = (): ParameterInterfaces => {
path: [],
formData: [],
body: []
}
}
};
};


export function generateOpenApiParams(options: OpenAPIOptions, path: string, pathItem: OpenAPIPathItem): t.TSInterfaceDeclaration[] {
Expand Down Expand Up @@ -253,7 +237,7 @@ export function generateOpenApiParams(options: OpenAPIOptions, path: string, pat
p.optional = true;
}
inner.push(p);
})
});

if (!options.mergedParams) {
if (paramType === 'body') {
Expand All @@ -272,7 +256,7 @@ export function generateOpenApiParams(options: OpenAPIOptions, path: string, pat
if (inner.length) {
props.push(
p
)
);
}
}
} else {
Expand Down Expand Up @@ -312,15 +296,15 @@ export function getOpenApiParams(options: OpenAPIOptions, path: string, pathItem
pathItem.parameters = pathItem.parameters ?? [];
const pathParms = pathItem.parameters?.filter(param => param.in === 'path') ?? [];
if (pathParms.length !== pathInfo.params.length) {
const parameters = pathItem.parameters?.filter(param => param.in !== 'path') ?? []
const parameters = pathItem.parameters?.filter(param => param.in !== 'path') ?? [];
pathInfo.params.forEach(name => {
const found = pathParms.find(param => param.name === name);
parameters.push(found ? found : {
name,
type: 'string',
required: true,
in: 'path'
})
});
});
pathItem.parameters = parameters;
}
Expand Down Expand Up @@ -358,7 +342,7 @@ export function getOpenApiParams(options: OpenAPIOptions, path: string, pathItem
if (operation.parameters) {
// Categorize parameters by 'in' field
operation.parameters.forEach(param => {
opParamMethod[param.in].push(param)
opParamMethod[param.in].push(param);
});
}

Expand All @@ -373,13 +357,13 @@ export function generateOpenApiTypes(options: OpenAPIOptions, schema: OpenAPISpe
Object.entries(schema.paths).forEach(([path, pathItem]) => {
interfaces.push(...generateOpenApiParams(options, path, pathItem));
});
return interfaces.map(i => t.exportNamedDeclaration(i))
return interfaces.map(i => t.exportNamedDeclaration(i));
}

const getOperationMethodName = (operation: Operation, method: string, path: string) => {
const methodName = operation.operationId || toCamelCase(method + path.replace(/\W/g, '_'));
return methodName;
}
};

export function generateMethods(options: OpenAPIOptions, schema: OpenAPISpec): t.ClassMethod[] {
const methods: t.ClassMethod[] = [];
Expand All @@ -398,7 +382,7 @@ export function generateMethods(options: OpenAPIOptions, schema: OpenAPISpec): t

const typeName = toPascalCase(getOperationMethodName(operation, method, path)) + 'Request';
const id = t.identifier('params');
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)))
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
const params = [id];

const returnType = getOperationReturnType(options, operation, method);
Expand Down Expand Up @@ -491,7 +475,7 @@ export function generateOpenApiClient(options: OpenAPIOptions, schema: OpenAPISp
true
),
...generateMethods(options, schema)
]
];

const classBody = t.classBody([
t.classMethod(
Expand Down
61 changes: 0 additions & 61 deletions packages/schema-sdk/src/template.literal.test.ts

This file was deleted.

37 changes: 37 additions & 0 deletions packages/schema-sdk/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import deepmerge from 'deepmerge';
import type { DeepPartial } from 'schema-typescript';
import { defaultSchemaTSOptions, SchemaTSOptions } from 'schema-typescript';

export interface OpenAPIOptions extends SchemaTSOptions {
version?: 'v1' | 'v1beta1' | 'v2beta1' | 'v2beta2';
mergedParams?: boolean;
paths?: {
// Include/Exclude types
include?: string[];
exclude?: string[];

includeTags?: string[];
excludeTags?: string[];

includeRequests?: string[];
excludeRequests?: string[];
}
}

export const defaultSchemaSDKOptions: OpenAPIOptions = {
...defaultSchemaTSOptions,
mergedParams: false,
paths: {
include: [],
exclude: [],
includeTags: [],
excludeTags: [],
includeRequests: [],
excludeRequests: []
}
};

export const getDefaultSchemaSDKOptions = (options?: DeepPartial<SchemaTSOptions>): SchemaTSOptions => {
return deepmerge(defaultSchemaSDKOptions, options ?? {}) as SchemaTSOptions;
};

8 changes: 4 additions & 4 deletions packages/schema-typescript/__tests__/additional-props.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ it('additional', () => {
},
required: ['firstName', 'lastName'],
additionalProperties: true
} as any)).toMatchSnapshot()
})
} as any)).toMatchSnapshot();
});

it('additional', () => {
expect(generateTypeScript({
Expand All @@ -43,5 +43,5 @@ it('additional', () => {
required: ['newProp'],
additionalProperties: true
}
} as any)).toMatchSnapshot()
})
} as any)).toMatchSnapshot();
});
4 changes: 2 additions & 2 deletions packages/schema-typescript/__tests__/const.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ it('const', () => {
},
required: ['firstName', 'age'],
additionalProperties: true
} as any)).toMatchSnapshot()
})
} as any)).toMatchSnapshot();
});
Loading

0 comments on commit 347ddfa

Please sign in to comment.