UNPKG

json-schema-to-joi

Version:

Converts JSON schema to Joi typescript code

88 lines 3.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatJoi = void 0; const prettier = require("prettier"); const _ = require("lodash"); const types_1 = require("./types"); function formatJoi(statements, options) { let title = ''; let result = ''; let skipStringCount = 0; const semi = false; const importedJoiName = (options ? options.joiName : 'Joi') || 'Joi'; const importedExtendedJoiName = (options ? options.extendedJoiName : 'extendedJoi') || 'extendedJoi'; const withExport = options ? options.withExport : false; const withTypeDeclaration = options ? options.withTypeDeclaration : false; statements.forEach((statement, i, all) => { if (typeof statement === 'string') { if (skipStringCount) { skipStringCount--; return; } result += statement; } else { switch (statement) { case 0: break; case 1: break; case 2: skipStringCount += 2; title = all[i + 1]; const type = all[i + 2]; const close = all[i + 3]; let typeString = ''; if (typeof title !== 'string' || close !== 3) { throw new Error('title not exist'); } if (withTypeDeclaration) { typeString = types_1.getJoiTsType(type); } result += `${withExport ? 'export' : ''} ` + `const ${title}JoiSchema${typeString ? ': ' + importedJoiName + '.' + typeString : ''} = `; break; case 3: break; case 200: result += importedJoiName + '.'; break; case 201: result += importedExtendedJoiName + '.'; break; case 4: case 5: case 6: let referKey = all[i + 1]; skipStringCount += 1; if (typeof referKey !== 'string') { throw new Error('reference has no key'); } const id = JSON.stringify('#' + referKey); referKey += 'JoiSchema'; if (statement === 5) { result += `${importedJoiName}.lazy(() => ${referKey})`; } else if (statement === 6) { result += `${importedJoiName}.link(${id})`; } else { result += referKey; } break; } } }); const prettierOptions = _.defaults({}, options ? options.prettierOptions : {}, { tabWidth: 2, useTabs: false, singleQuote: true, trailingComma: 'all', semi, parser: 'typescript', printWidth: 80, }); return prettier.format(result, prettierOptions); } exports.formatJoi = formatJoi; //# sourceMappingURL=format.js.map