Skip to content

Commit

Permalink
Create spec for Union types
Browse files Browse the repository at this point in the history
  • Loading branch information
gilgardosh committed Sep 13, 2023
1 parent 457520c commit dc8e1a0
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/open-api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isScalarType,
isEnumType,
GraphQLType,
isUnionType,
} from 'graphql';
import { mapToPrimitive, mapToRef } from './utils';

Expand Down Expand Up @@ -89,6 +90,12 @@ export function resolveFieldType(
};
}

if (isUnionType(type)) {
return {
oneOf: type.getTypes().map((type) => resolveFieldType(type, opts)),
};
}

return {
type: 'object',
};
Expand Down
72 changes: 72 additions & 0 deletions tests/open-api/operations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ const schema = buildSchema(/* GraphQL */ `
authorId: Int
}
type Image {
url: String
}
type Gallery {
id: ID
name: String
images: [Image!]!
}
union Inspiration = Post | Gallery
type Query {
"""
Feed of posts
Expand All @@ -30,6 +42,11 @@ const schema = buildSchema(/* GraphQL */ `
"""
type: PostType
): [Post]
"""
Random post or gallery
"""
inspiration: Inspiration
}
scalar Date
Expand Down Expand Up @@ -232,3 +249,58 @@ test('handle query params in POST requests', async () => {
},
});
});

test('handle union type', async () => {
const operation = buildOperationNodeForField({
schema,
kind: 'query' as OperationTypeNode,
field: 'inspiration',
models: [],
ignore: [],
});

const result = buildPathFromOperation({
url: '/api/inspiration',
operation: {
kind: Kind.DOCUMENT,
definitions: [operation],
},
schema,
useRequestBody: false,
customScalars: {
Date: { type: 'string', format: 'date' },
},
});
expect(result.operationId).toEqual('inspiration_query');
expect(result.parameters?.length).toEqual(2);
expect(result.parameters?.[0]).toEqual({
in: 'query',
name: 'inspiration_comments_filter',
required: true,
schema: {
type: 'string',
},
});
expect(result.parameters?.[1]).toEqual({
in: 'query',
name: 'inspiration_comments_date',
required: false,
schema: {
type: 'string',
format: 'date',
},
});

expect((result.responses[200] as any).description).toMatch(
'Random post or gallery'
);

const response = (result.responses[200] as any).content['application/json']
.schema;
expect(response).toEqual({
oneOf: [
{ $ref: '#/components/schemas/Post' },
{ $ref: '#/components/schemas/Gallery' },
],
});
});

0 comments on commit dc8e1a0

Please sign in to comment.