Skip to content

Commit a6e974f

Browse files
authored
feat(sync): Add convert sync method (#52)
* feat(sync): Add convertSync method for converting json schema to openapi schema * test(sync): Add comprehensive test cases for convertSync function - Synchronous versions of const, if-then-else, nullable, pattern properties - Error handling for invalid types and malformed schemas - External reference handling (no deref support) - Options testing (skip unreferenced definitions) - Stress test with many definitions * docs: Add comprehensive documentation for convertSync function - Add Synchronous API section with usage example - Document supported options (cloneSchema, convertUnreferencedDefinitions) - Include clear limitations section with example of external reference handling - Explain when to use convertSync vs convert
1 parent cf87a1e commit a6e974f

File tree

4 files changed

+396
-2
lines changed

4 files changed

+396
-2
lines changed

README.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,74 @@ Options:
8686
-d, --dereference If set all local and remote references (http/https and file) $refs will be dereferenced
8787
```
8888

89+
## Synchronous API
90+
91+
For synchronous conversion without async operations, use `convertSync`:
92+
93+
```ts
94+
import { convertSync } from '@openapi-contrib/json-schema-to-openapi-schema';
95+
96+
const schema = {
97+
$schema: 'http://json-schema.org/draft-04/schema#',
98+
type: ['string', 'null'],
99+
format: 'date-time',
100+
};
101+
102+
const convertedSchema = convertSync(schema);
103+
console.log(convertedSchema);
104+
```
105+
106+
This will output the same result as the async version:
107+
108+
```js
109+
{
110+
type: 'string',
111+
format: 'date-time',
112+
nullable: true
113+
}
114+
```
115+
116+
### Options for convertSync
117+
118+
`convertSync` supports a subset of the options available to `convert`:
119+
120+
#### `cloneSchema` (boolean)
121+
122+
If set to `false`, converts the provided schema in place. If `true`, clones the schema by converting it to JSON and back. The overhead of the cloning is usually negligible. Defaults to `true`.
123+
124+
#### `convertUnreferencedDefinitions` (boolean)
125+
126+
Defaults to `true`.
127+
128+
If a schema has a `definitions` property (valid in JSON Schema), and only some entries are referenced, we'll still try to convert the remaining definitions to OpenAPI. If you do not want this behavior, set this to `false`.
129+
130+
### ⚠️ Limitations
131+
132+
`convertSync` does **not** support dereferencing external references (`$ref` to HTTP/HTTPS URLs or external files). If your schema contains external references, use the async `convert` function with the `dereference: true` option instead.
133+
134+
#### Example:
135+
136+
```ts
137+
// Schema with external reference
138+
const schema = {
139+
type: 'object',
140+
properties: {
141+
user: {
142+
$ref: 'https://example.com/schemas/user.json',
143+
},
144+
},
145+
};
146+
147+
// convertSync leaves the reference unresolved
148+
const result = convertSync(schema);
149+
// Result: { type: 'object', properties: { user: { $ref: 'https://example.com/schemas/user.json' } } }
150+
151+
// Use async convert for proper resolution:
152+
const resolved = await convert(schema, { dereference: true });
153+
```
154+
155+
**Note:** External references will remain as `$ref` pointers in the output schema. They will not be expanded or validated.
156+
89157
## Why?
90158

91159
OpenAPI is often described as an extension of JSON Schema, but both specs have changed over time and grown independently. OpenAPI v2 was based on JSON Schema draft v4 with a long list of deviations, but OpenAPI v3 shrank that list, upping their support to draft v4 and making the list of discrepancies shorter. This has been solved for OpenAPI v3.1, but for those using OpenAPI v3.0, you can use this tool to solve [the divergence](https://apisyouwonthate.com/blog/openapi-and-json-schema-divergence).

src/index.ts

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import type {
33
JSONSchema6Definition,
44
JSONSchema7Definition,
55
} from 'json-schema';
6-
import type { Options, SchemaType, SchemaTypeKeys } from './types';
6+
import type { Options, OptionsSync, SchemaType, SchemaTypeKeys } from './types';
77
import { Walker } from 'json-schema-walker';
88
import { allowedKeywords } from './const';
9-
import type { OpenAPIV3 } from 'openapi-types';
9+
import { type OpenAPIV3 } from 'openapi-types';
1010
import type { JSONSchema } from '@apidevtools/json-schema-ref-parser';
1111

1212
class InvalidTypeError extends Error {
@@ -70,6 +70,51 @@ const handleDefinition = async <T extends JSONSchema4 = JSONSchema4>(
7070
return def;
7171
};
7272

73+
const handleDefinitionSync = <T extends JSONSchema4 = JSONSchema4>(
74+
def: JSONSchema7Definition | JSONSchema6Definition | JSONSchema4,
75+
schema: T,
76+
) => {
77+
if (typeof def !== 'object') {
78+
return def;
79+
}
80+
81+
const type = def.type;
82+
if (type) {
83+
// Walk just the definitions types
84+
const walker = new Walker<T>();
85+
walker.loadSchemaSync(
86+
{
87+
definitions: schema['definitions'] || [],
88+
...def,
89+
$schema: schema['$schema'],
90+
} as any,
91+
{
92+
cloneSchema: true,
93+
},
94+
);
95+
walker.walkSync(convertSchema, walker.vocabularies.DRAFT_07);
96+
if ('definitions' in walker.rootSchema) {
97+
delete (<any>walker.rootSchema).definitions;
98+
}
99+
return walker.rootSchema;
100+
}
101+
if (Array.isArray(def)) {
102+
// if it's an array, we might want to reconstruct the type;
103+
const typeArr = def;
104+
const hasNull = typeArr.includes('null');
105+
if (hasNull) {
106+
const actualTypes = typeArr.filter((l) => l !== 'null');
107+
return {
108+
type: actualTypes.length === 1 ? actualTypes[0] : actualTypes,
109+
nullable: true,
110+
// this is incorrect but thats ok, we are in the inbetween phase here
111+
} as JSONSchema7Definition | JSONSchema6Definition | JSONSchema4;
112+
}
113+
}
114+
115+
return def;
116+
};
117+
73118
export const convert = async <T extends object = JSONSchema4>(
74119
schema: T,
75120
options?: Options,
@@ -89,6 +134,25 @@ export const convert = async <T extends object = JSONSchema4>(
89134
return rootSchema as OpenAPIV3.Document;
90135
};
91136

137+
export const convertSync = <T extends object = JSONSchema4>(
138+
schema: T,
139+
options?: OptionsSync,
140+
): OpenAPIV3.Document => {
141+
const walker = new Walker<T>();
142+
const convertDefs = options?.convertUnreferencedDefinitions ?? true;
143+
walker.loadSchemaSync(schema, options);
144+
walker.walkSync(convertSchema, walker.vocabularies.DRAFT_07);
145+
// if we want to convert unreferenced definitions, we need to do it iteratively here
146+
const rootSchema = walker.rootSchema as unknown as JSONSchema;
147+
if (convertDefs && rootSchema?.definitions) {
148+
for (const defName in rootSchema.definitions) {
149+
const def = rootSchema.definitions[defName];
150+
rootSchema.definitions[defName] = handleDefinitionSync(def, schema);
151+
}
152+
}
153+
return rootSchema as OpenAPIV3.Document;
154+
};
155+
92156
function stripIllegalKeywords(schema: SchemaType) {
93157
if (typeof schema !== 'object') {
94158
return schema;

src/types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ export interface Options {
1111
convertUnreferencedDefinitions?: boolean;
1212
dereferenceOptions?: ParserOptions | undefined;
1313
}
14+
15+
export interface OptionsSync {
16+
cloneSchema?: boolean;
17+
convertUnreferencedDefinitions?: boolean;
18+
}
19+
1420
type ExtendedJSONSchema = addPrefixToObject & JSONSchema;
1521
export type SchemaType = ExtendedJSONSchema & {
1622
example?: JSONSchema['examples'][number];

0 commit comments

Comments
 (0)