UNPKG

graphql-2-json-schema

Version:
52 lines (51 loc) 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.graphqlToJSONType = exports.scalarToJsonType = exports.ID_TYPE_MAPPING_OPTION_DEFAULT = void 0; const lodash_1 = require("lodash"); const typeGuards_1 = require("./typeGuards"); exports.ID_TYPE_MAPPING_OPTION_DEFAULT = 'string'; const ID_TYPES = { string: 'string', number: 'number', both: ['string', 'number'], }; const SCALAR_TO_JSON = { Boolean: 'boolean', String: 'string', Int: 'number', Float: 'number', ID: ID_TYPES[exports.ID_TYPE_MAPPING_OPTION_DEFAULT], }; const scalarToJsonType = (scalarName, options = {}) => Object.assign({}, SCALAR_TO_JSON, { ID: ID_TYPES[options.idTypeMapping || exports.ID_TYPE_MAPPING_OPTION_DEFAULT], })[scalarName]; exports.scalarToJsonType = scalarToJsonType; const graphqlToJSONType = (k, options = {}) => { if (typeGuards_1.isIntrospectionListTypeRef(k)) { return { type: 'array', items: exports.graphqlToJSONType(k.ofType, Object.assign(Object.assign({}, options), { isArray: true })), }; } else if (typeGuards_1.isNonNullIntrospectionType(k)) { return exports.graphqlToJSONType(k.ofType, Object.assign(Object.assign({}, options), { isNonNull: true })); } else { const name = k.name; const { isArray, isNonNull, nullableArrayItems } = options; const jsonType = {}; if (lodash_1.includes(typeGuards_1.SUPPORTED_KINDS, k.kind)) { jsonType.$ref = `#/definitions/${name}`; } else { jsonType.type = exports.scalarToJsonType(name, options); } if (nullableArrayItems && isArray && !isNonNull) { return { anyOf: [jsonType, { type: 'null' }], }; } return jsonType; } }; exports.graphqlToJSONType = graphqlToJSONType;