Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zp/discriminator types #1

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20,044 changes: 20,044 additions & 0 deletions packages/openapi-to-graphql/package-lock.json

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions packages/openapi-to-graphql/src/schema_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,26 @@ function createOrReuseUnion<TSource, TContext, TArgs>({
description,
types,
resolveType: (source, context, info) => {

if (def.schema.discriminator) {
// Get the discriminator property name and then use that property to inspect
// the properties on the field that we have, matching the value to one of the
// type.

const componentName = source[def.schema.discriminator.propertyName]

const { mapping } = def.schema.discriminator

const type = types.find((type) => {
if (!mapping[componentName]) {
return false
}
return mapping[componentName].includes(type.name)
})
if (type) return type
return null
}

const properties = Object.keys(source)
// Remove custom _openAPIToGraphQL property used to pass data
.filter((property) => property !== '_openAPIToGraphQL')
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-to-graphql/src/types/oas3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type SchemaObject = {
type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array'
format?: string
nullable?: boolean
discriminator?: DiscriminatorObject
description?: string
properties?: {
[key: string]: SchemaObject | ReferenceObject
Expand Down Expand Up @@ -63,6 +64,13 @@ type EncodingObject = {
allowReserved?: boolean
}

type DiscriminatorObject = {
propertyName: string
mapping: {
[key: string]: string
}
}

export type MediaTypeObject = {
schema?: SchemaObject | ReferenceObject
example?: any
Expand Down
116 changes: 116 additions & 0 deletions packages/openapi-to-graphql/test/discriminator_union.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: openapi-to-graphql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict'

import { graphql } from 'graphql'
import { afterAll, beforeAll, expect, test } from '@jest/globals'

import * as openAPIToGraphQL from '../src/index'
import { startServer, stopServer } from './discriminator_union_server'

const oas = require('./fixtures/oneof_type_union.json')
const PORT = 3004
// Update PORT for this test case:
oas.servers[0].variables.port.default = String(PORT)

let createdSchema

/**
* Set up the schema first and run example API server
*/
beforeAll(() => {
return Promise.all([
openAPIToGraphQL.createGraphQLSchema(oas).then(({ schema, report }) => {
console.log(report)
createdSchema = schema
}),
startServer(PORT)
])
})

/**
* Shut down API server
*/
afterAll(() => {
return stopServer()
})

test('Querying a type union that uses a discriminator type', () => {
const query = `query {
shapes {
__typename
... on SquareShapeOptions {
height
width
}
... on RoundShapeOptions {
radius
}
... on DotShapeOptions {
radius
x
y
}
}
}`
return graphql(createdSchema, query).then((result) => {
expect(result).toEqual({
data: {
shapes: [
{
__typename: 'SquareShapeOptions',
height: 10,
width: 20
},
{
__typename: 'RoundShapeOptions',
radius: 30
},
{
__typename: 'DotShapeOptions',
radius: 50,
x: 1,
y: 2
}
]
}
})
})
})

// test('Posting a type union', () => {
// // Supposedly this is the best we can do with GraphQL mutations and type
// // unions?
// //
// // See https://github.com/graphql/graphql-spec/issues/488
// const query = `mutation {
// createShape (shapeOptionsPostInput: {
// type: "square"
// width: 50
// height: 50
// }) {
// __typename
// ... on SquareShapeOptions {
// height
// width
// }
// ... on RoundShapeOptions {
// radius
// }
// }
// }`
// return graphql(createdSchema, query).then((result) => {
// expect(result).toEqual({
// data: {
// createShape: {
// __typename: 'SquareShapeOptions',
// height: 50,
// width: 50
// }
// }
// })
// })
// })
72 changes: 72 additions & 0 deletions packages/openapi-to-graphql/test/discriminator_union_server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: openapi-to-graphql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict'

let server // holds server object for shutdown

/**
* Starts the server at the given port
*/
function startServer(PORT) {
const express = require('express')
const app = express()

const bodyParser = require('body-parser')
app.use(bodyParser.json())

app.get('/api/shapes', (req, res) => {
res.send([
{
type: 'square',
height: 10,
width: 20
},
{
type: 'round',
radius: 30
},
{
type: 'dot',
radius: 50,
x: 1,
y: 2
}
])
})

app.post('/api/shapes', (req, res) => {
res.send(req.body)
})

return new Promise((resolve) => {
server = app.listen(PORT, () => {
console.log(`Example API accessible on port ${PORT}`)
resolve()
})
})
}

/**
* Stops server.
*/
function stopServer() {
return new Promise((resolve) => {
server.close(() => {
console.log(`Stopped API server`)
resolve()
})
})
}

// If run from command line, start server:
if (require.main === module) {
startServer(3002)
}

module.exports = {
startServer,
stopServer
}
Loading