@weverson_na/prisma-generator-nestjs-dto
Version:
Advanced Prisma Generator with Smart Merge v2: Creates DTO and Entity classes with AST-based preservation, intelligent import management, and modular architecture for NestJS
193 lines (192 loc) • 7.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateHelpers = void 0;
const decorator_strategy_1 = require("./decorator-strategy");
class TemplateHelpers {
constructor(options) {
this.decoratorStrategy = new decorator_strategy_1.DecoratorStrategy();
const { connectDtoPrefix, createDtoPrefix, updateDtoPrefix, dtoSuffix, entityPrefix, entitySuffix, transformClassNameCase = (s) => s, transformFileNameCase = (s) => s, } = options;
this.connectDtoPrefix = connectDtoPrefix;
this.createDtoPrefix = createDtoPrefix;
this.updateDtoPrefix = updateDtoPrefix;
this.dtoSuffix = dtoSuffix;
this.entityPrefix = entityPrefix;
this.entitySuffix = entitySuffix;
this.transformClassNameCase = transformClassNameCase;
this.transformFileNameCase = transformFileNameCase;
}
static scalarToTS(scalar, useInputTypes = false) {
if (!TemplateHelpers.knownPrismaScalarTypes.includes(scalar)) {
throw new Error(`Unrecognized scalar type: ${scalar}`);
}
if (useInputTypes && scalar === 'Json') {
return 'Prisma.InputJsonValue';
}
return TemplateHelpers.PrismaScalarToTypeScript[scalar];
}
static echo(input) {
return input;
}
static when(condition, thenTpl, elseTpl = '') {
return condition ? thenTpl : elseTpl;
}
static unless(condition, thenTpl, elseTpl = '') {
return !condition ? thenTpl : elseTpl;
}
static each(arr, fn, joinWith = '') {
return arr.map(fn).join(joinWith);
}
static importStatement(input) {
const { from, destruct = [], default: def } = input;
const parts = ['import'];
if (def) {
parts.push(typeof def === 'string' ? def : `* as ${def['*']}`);
}
if (destruct.length) {
if (def)
parts.push(',');
const inside = destruct
.flatMap((item) => typeof item === 'string'
? [item]
: Object.entries(item).map(([orig, alias]) => `${orig} as ${alias}`))
.join(', ');
parts.push(`{ ${inside} }`);
}
parts.push(`from '${from}'`);
return parts.join(' ');
}
static importStatements(items) {
return TemplateHelpers.each(items, TemplateHelpers.importStatement, '\n');
}
className(name, prefix = '', suffix = '') {
return `${prefix}${this.transformClassNameCase(name)}${suffix}`;
}
fileName(name, prefix = '', suffix = '', withExt = false) {
return `${prefix}${this.transformFileNameCase(name)}${suffix}${TemplateHelpers.when(withExt, '.ts')}`;
}
entityName(name) {
return this.className(name, this.entityPrefix, this.entitySuffix);
}
connectDtoName(name) {
return this.className(name, this.connectDtoPrefix, this.dtoSuffix);
}
createDtoName(name) {
return this.className(name, this.createDtoPrefix, this.dtoSuffix);
}
updateDtoName(name) {
return this.className(name, this.updateDtoPrefix, this.dtoSuffix);
}
connectDtoFilename(name, withExt = false) {
return this.fileName(name, 'connect-', '.dto', withExt);
}
createDtoFilename(name, withExt = false) {
return this.fileName(name, 'create-', '.dto', withExt);
}
updateDtoFilename(name, withExt = false) {
return this.fileName(name, 'update-', '.dto', withExt);
}
entityFilename(name, withExt = false) {
return this.fileName(name, undefined, '.entity', withExt);
}
fieldType(field, toInputType = false) {
switch (field.kind) {
case 'scalar':
return TemplateHelpers.scalarToTS(field.type, toInputType);
case 'enum':
case 'relation-input':
return field.type;
default:
return `${this.entityName(field.type)}${TemplateHelpers.when(field.isList, '[]')}`;
}
}
static hasSomeApiPropertyDoc(fields) {
return fields.some((f) => TemplateHelpers.hasApiPropertyDoc(f));
}
static hasApiPropertyDoc(field) {
var _a;
return Boolean((_a = field.documentation) === null || _a === void 0 ? void 0 : _a.includes('@ApiProperty'));
}
addDecorator(field, isEntity = false) {
return isEntity
? this.buildEntityDecorator(field)
: this.buildDtoDecorator(field);
}
buildEntityDecorator(field) {
var _a;
if (!TemplateHelpers.hasApiPropertyDoc(field)) {
return '';
}
const apiPropertyLines = ((_a = field.documentation) !== null && _a !== void 0 ? _a : '')
.split('\n')
.filter((line) => line.includes('@ApiProperty'))
.map((line) => line.trim());
return apiPropertyLines.join('\n') + (apiPropertyLines.length ? '\n' : '');
}
buildDtoDecorator(field) {
if (field.kind === 'enum') {
return this.buildEnumDecorator(field);
}
if (['scalar', 'relation-input', 'object'].includes(field.kind)) {
return this.buildFieldDecorator(field);
}
return '';
}
buildEnumDecorator(field) {
var _a;
const isValid = this.decoratorStrategy.verifyIfDecoratorIsValid((_a = field.documentation) !== null && _a !== void 0 ? _a : '');
return isValid
? `${field.documentation}\n`
: `@ApiProperty({ enum: ${this.fieldType(field)} })\n`;
}
buildFieldDecorator(field) {
var _a;
const isValid = this.decoratorStrategy.verifyIfDecoratorIsValid((_a = field.documentation) !== null && _a !== void 0 ? _a : '');
return isValid ? `${field.documentation}\n` : '';
}
fieldToDtoProp(field, useInputTypes = false, forceOptional = false, addExposePropertyDecorator = false) {
const optionalMark = TemplateHelpers.unless(field.isRequired && !forceOptional, '?');
return (this.addDecorator(field) +
(addExposePropertyDecorator ? `@Expose()\n` : '') +
`${field.name}${optionalMark}: ${this.fieldType(field, useInputTypes)};`);
}
fieldsToDtoProps(fields, useInputTypes = false, forceOptional = false, addExposePropertyDecorator = false) {
return TemplateHelpers.each(fields, (f) => this.fieldToDtoProp(f, useInputTypes, forceOptional, addExposePropertyDecorator), '\n');
}
fieldToEntityProp(field) {
const opt = TemplateHelpers.unless(field.isRequired, '?');
const nullable = TemplateHelpers.when(field.isNullable, ' | null');
return (this.addDecorator(field, true) +
`${field.name}${opt}: ${this.fieldType(field)}${nullable};`);
}
fieldsToEntityProps(fields) {
return TemplateHelpers.each(fields, (f) => this.fieldToEntityProp(f), '\n');
}
apiExtraModels(names) {
const list = names.map((n) => this.entityName(n)).join(', ');
return `@ApiExtraModels(${list})`;
}
get config() {
const { connectDtoPrefix, createDtoPrefix, updateDtoPrefix, dtoSuffix, entityPrefix, entitySuffix, } = this;
return {
connectDtoPrefix,
createDtoPrefix,
updateDtoPrefix,
dtoSuffix,
entityPrefix,
entitySuffix,
};
}
}
exports.TemplateHelpers = TemplateHelpers;
TemplateHelpers.PrismaScalarToTypeScript = {
String: 'string',
Boolean: 'boolean',
Int: 'number',
BigInt: 'bigint',
Float: 'number',
Decimal: 'Prisma.Decimal',
DateTime: 'Date',
Json: 'Prisma.JsonValue',
Bytes: 'Buffer',
};
TemplateHelpers.knownPrismaScalarTypes = Object.keys(TemplateHelpers.PrismaScalarToTypeScript);