UNPKG

@sprucelabs/schema

Version:

Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓

87 lines (86 loc) • 2.98 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fields_1 = require("./fields"); const template_types_1 = require("./types/template.types"); const assertOptions_1 = __importDefault(require("./utilities/assertOptions")); class SchemaTypesRenderer { static Renderer() { return new this(); } render(schema, options) { (0, assertOptions_1.default)({ schema, options }, ['schema', 'options']); const { id, fields } = schema; const { schemaTemplateItems } = options; const name = this.renderName(id); const comment = this.renderComment(schema); let body = ''; for (const [key, field] of Object.entries(fields ?? {})) { let fieldLine = this.renderField(field, key, schemaTemplateItems); body += fieldLine; } return `${comment ? `${comment}\n` : ''}type ${name} struct { ${body}}`; } renderName(id) { return this.ucFirst(id); } renderField(field, key, schemaTemplateItems = []) { const FieldClass = fields_1.fieldClassMap[field.type]; const { valueType, validation } = FieldClass.generateTemplateDetails({ //@ts-ignore definition: field, language: 'go', importAs: 'SpruceSchema', templateItems: schemaTemplateItems, renderAs: template_types_1.TemplateRenderAs.Type, }); const { hint, isRequired, minArrayLength, isArray } = field; let fieldLine = ''; if (hint) { fieldLine += '\t// ' + hint + '\n'; } fieldLine += '\t' + this.ucFirst(key) + ' ' + valueType + ' `json:"' + key; const validateTags = []; if (isRequired) { validateTags.push('required'); } if ((isArray && isRequired) || minArrayLength !== undefined) { validateTags.push(`min=${minArrayLength ?? 1}`); } if (!isRequired) { fieldLine += ',omitempty"'; } else { fieldLine += '"'; } if (validation && isArray) { validateTags.push('dive'); } if (validation) { validateTags.push(...validation); } if (validateTags.length) { fieldLine += ' validate:"' + validateTags.join(',') + '"'; } fieldLine += '`\n'; return fieldLine; } renderComment(schema) { let comment = ''; if (schema.name) { comment = `// ${schema.name}`; } if (schema.description) { comment += `${schema.name ? ': ' : '// '}${schema.description}`; } return comment; } ucFirst(str) { return str.charAt(0).toUpperCase() + str.slice(1); } } exports.default = SchemaTypesRenderer;