UNPKG

@sprucelabs/schema

Version:

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

81 lines (80 loc) • 2.79 kB
import { fieldClassMap } from './fields/index.js'; import { TemplateRenderAs, } from './types/template.types.js'; import assertOptions from './utilities/assertOptions.js'; export default class SchemaTypesRenderer { static Renderer() { return new this(); } render(schema, options) { assertOptions({ 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 !== null && fields !== void 0 ? 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 = fieldClassMap[field.type]; const { valueType, validation } = FieldClass.generateTemplateDetails({ //@ts-ignore definition: field, language: 'go', importAs: 'SpruceSchema', templateItems: schemaTemplateItems, renderAs: 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 !== null && minArrayLength !== void 0 ? 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); } }