@udraft/core
Version:
uDraft is a language and stack agnostic code-generation tool that simplifies full-stack development by converting a single YAML file into code for rapid development.
184 lines • 9.22 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const renderer_1 = require("../entities/renderer");
const package_1 = require("../helpers/package");
const queries_1 = require("../shortcuts/queries");
const rendering_1 = require("../utils/rendering");
const attributes_1 = require("../shortcuts/attributes");
const KEYS = {
packageJson: "packageJson",
};
class TSClassValidatorRenderer extends renderer_1.URenderer {
constructor(options) {
super("ts@class-validators");
this._updatePackageJson = false;
if (options === null || options === void 0 ? void 0 : options.where)
this._where = options.where;
if (options === null || options === void 0 ? void 0 : options.updatePackageJson)
this._updatePackageJson = options.updatePackageJson;
}
select() {
return __awaiter(this, void 0, void 0, function* () {
this._classRenderer = this.$draft().$requireRenderer(this, "ts@classes");
const models = this.$models(this._where).filter((model) => !!this._classRenderer.$output(this._classRenderer.$key(model)));
const paths = [...this._classRenderer.$paths(models)];
if (this._updatePackageJson)
paths.push({
key: KEYS.packageJson,
path: "package.json",
});
return {
paths,
models,
};
});
}
render() {
return __awaiter(this, void 0, void 0, function* () {
const output = [];
if (this._updatePackageJson)
output.push({
key: KEYS.packageJson,
content: (0, package_1.addPackageJsonDependency)(this.$content("packageJson").content, [
{
name: "class-validator",
version: "^0.14.1",
},
]),
});
const models = this.$selection().models || [];
models.forEach((model) => {
var _a, _b;
if (!!(0, queries_1.$attr)(model, (0, attributes_1._enum)()))
return;
const modelKey = this._classRenderer.$key(model);
let content = ((_a = this.$content(modelKey)) === null || _a === void 0 ? void 0 : _a.content) || "";
if (!content)
return;
const fields = model.$fields();
const importedValidators = [];
const importValidator = (validator) => {
if (!validator)
return;
if (!importedValidators.includes(validator))
importedValidators.push(validator);
};
for (let field of fields) {
const fieldCursor = ` ${this._classRenderer.$fieldSignature(field)};\n`;
const attributes = [
{
attr: (0, attributes_1._required)(),
value: (val) => val === true ? `@IsDefined()` : `@IsOptional()`,
},
{
attr: (0, attributes_1._min)(),
value: (val) => `@Min(${val})`,
},
{
attr: (0, attributes_1._max)(),
value: (val) => `@Max(${val})`,
},
{
attr: (0, attributes_1._minLength)(),
value: (val) => `@MinLength(${val})`,
},
{
attr: (0, attributes_1._maxLength)(),
value: (val) => `@MaxLength(${val})`,
},
{
attr: (0, attributes_1._notEmpty)(),
value: (val) => (val === true ? `@IsNotEmpty()` : ""),
},
{
attr: (0, attributes_1._size)(),
value: (val) => `@Length(${val})`,
},
{
attr: (0, attributes_1._in)(),
value: (val) => `@IsIn(${JSON.stringify(val)})`,
},
{
attr: (0, attributes_1._notIn)(),
value: (val) => `@IsNotIn(${JSON.stringify(val)})`,
},
{
attr: (0, attributes_1._array)(),
value: (val) => (val === true ? `@IsArray()` : ""),
},
{
attr: (0, attributes_1._regex)(),
value: (val) => `@Matches(${val.toString()})`,
},
];
for (let attribute of attributes) {
// if (attribute.attr.$name() == "array") debugger;
const value = (0, queries_1.$attr)(field, attribute.attr);
if (value !== null) {
const decorator = attribute.value(value);
if (decorator) {
importValidator(decorator.match(/@(\w+)/)[1]);
content = (0, rendering_1.writeToCursor)(fieldCursor, ` ${decorator}\n`, content);
}
}
}
let decorator = "";
let validationOptions = "";
if ((0, queries_1.$attr)(field, (0, attributes_1._array)()) === true)
validationOptions = "{each: true}";
if (field.$type() === "string")
decorator = `@IsString(${validationOptions})`;
else if (field.$type() === "number")
decorator = `@IsNumber(${validationOptions ? "{}, " + validationOptions : ""})`;
else if (field.$type() === "boolean")
decorator = `@IsBoolean(${validationOptions})`;
else if (field.$type() === "date")
decorator = `@IsDate(${validationOptions})`;
else if (field.$type() === "int")
decorator = `@IsInt(${validationOptions})`;
else if (field.$type() === "float")
decorator = `@IsNumber(${validationOptions ? "{}, " + validationOptions : ""})`;
else if (field.$type() === "nested") {
const nestedModel = (0, queries_1.$attr)(field, (0, attributes_1._ref)());
if (nestedModel) {
if ((0, queries_1.$attr)(nestedModel, (0, attributes_1._enum)())) {
decorator = `@IsEnum(${this._classRenderer.$className(nestedModel)}${validationOptions ? ", " + validationOptions : ""})`;
}
else
decorator = `@ValidateNested(${validationOptions})`;
}
}
if (decorator) {
importValidator((_b = decorator.match(/@(\w+)/)) === null || _b === void 0 ? void 0 : _b[1]);
content = (0, rendering_1.writeToCursor)(fieldCursor, ` ${decorator}\n`, content);
}
if (!content.includes(fieldCursor + "}"))
content = content.replace(fieldCursor, fieldCursor + `\n`);
}
content =
`import {\n${importedValidators
.map((v) => " " + v + ",\n")
.join("")
.replace(/,\n$/, "\n")}} from "class-validator";\n` +
(!content.match("^import") ? "\n" : "") +
content;
output.push({
key: modelKey,
content,
});
});
return output;
});
}
}
exports.default = TSClassValidatorRenderer;
//# sourceMappingURL=ts-class-validator-renderer.js.map