UNPKG

get-graphql-from-jsonschema

Version:

get-graphql-from-jsonschema gets a GraphQL schema from a JSON schema.

66 lines (65 loc) 2.91 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.handleObjectType = void 0; const parseSchema_1 = require("./parseSchema"); const toBreadcrumb_1 = require("./toBreadcrumb"); const toPascalCase_1 = require("./toPascalCase"); const errors = __importStar(require("./errors")); const handleObjectType = function ({ path, schema, direction }) { var _a; const graphqlTypeName = (0, toPascalCase_1.toPascalCase)(path); const graphqlTypeDefinitions = []; const lines = []; if (!('properties' in schema)) { throw new errors.SchemaInvalid(`Expected schema of type 'object' at '${(0, toBreadcrumb_1.toBreadcrumb)(path)}' to contain properties.`); } for (const [propertyName, propertySchema] of Object.entries(schema.properties)) { const isRequired = (_a = (schema.required && schema.required.includes(propertyName))) !== null && _a !== void 0 ? _a : false; const { typeName: propertyGraphqlTypeName, typeDefinitions: propertyGraphqlTypeDefinitions } = (0, parseSchema_1.parseSchema)({ path: [...path, propertyName], schema: propertySchema, direction }); let line = ` ${propertyName}: ${propertyGraphqlTypeName}`; line += isRequired ? '!\n' : '\n'; lines.push(line); graphqlTypeDefinitions.push(...propertyGraphqlTypeDefinitions); } let currentGraphqlTypeDefinition = ''; currentGraphqlTypeDefinition += direction === 'input' ? 'input' : 'type'; if (lines.length > 0) { currentGraphqlTypeDefinition += ` ${graphqlTypeName} {\n`; for (const line of lines) { currentGraphqlTypeDefinition += line; } currentGraphqlTypeDefinition += '}'; } else { currentGraphqlTypeDefinition += ` ${graphqlTypeName}`; } graphqlTypeDefinitions.push(currentGraphqlTypeDefinition); return { typeName: graphqlTypeName, typeDefinitions: graphqlTypeDefinitions }; }; exports.handleObjectType = handleObjectType;