Skip to content

Commit

Permalink
identified and fixed relations and pluralise issues
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoalbanese committed Nov 29, 2023
1 parent 20651e3 commit 83b4314
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 83 deletions.
60 changes: 34 additions & 26 deletions src/commands/generate/generators/model/queries/generators.ts
Expand Up @@ -26,24 +26,24 @@ import { eq${belongsToUser ? ", and" : ""} } from "drizzle-orm";${
belongsToUser
? `\nimport { getUserAuth } from "${formatFilePath(
shared.auth.authUtils,
{ prefix: "alias", removeExtension: true }
{ prefix: "alias", removeExtension: true },
)}";`
: ""
}
import { type ${tableNameSingularCapitalised}Id, ${tableNameSingular}IdSchema, ${tableNameCamelCase} } from "${formatFilePath(
shared.orm.schemaDir,
{ prefix: "alias", removeExtension: false }
{ prefix: "alias", removeExtension: false },
)}/${tableNameCamelCase}";
${
relations.length > 0
? relations.map(
(relation) =>
`import { ${toCamelCase(
relation.references
relation.references,
)} } from "${formatFilePath(shared.orm.schemaDir, {
prefix: "alias",
removeExtension: false,
})}/${toCamelCase(relation.references)}";\n`
})}/${toCamelCase(relation.references)}";\n`,
)
: ""
}`;
Expand All @@ -65,13 +65,13 @@ const generatePrismaImports = (schema: Schema) => {
belongsToUser
? `\nimport { getUserAuth } from "${formatFilePath(
shared.auth.authUtils,
{ prefix: "alias", removeExtension: true }
{ prefix: "alias", removeExtension: true },
)}";`
: ""
}
import { type ${tableNameSingularCapitalised}Id, ${tableNameSingular}IdSchema } from "${formatFilePath(
shared.orm.schemaDir,
{ removeExtension: false, prefix: "alias" }
{ removeExtension: false, prefix: "alias" },
)}/${tableNameCamelCase}";
`;
};
Expand All @@ -91,19 +91,21 @@ const generateDrizzleGetQuery = (schema: Schema, relations: DBField[]) => {
? `{ ${tableNameSingular}: ${tableNameCamelCase}, ${relations
.map(
(relation) =>
`${relation.references.slice(0, -1)}: ${relation.references}`
`${pluralize.singular(
toCamelCase(relation.references),
)}: ${toCamelCase(relation.references)}`,
)
.join(", ")} }`
: ""
}).from(${tableNameCamelCase})${
relations.length > 0
? relations.map(
(relation) =>
`.leftJoin(${
relation.references
}, eq(${tableNameCamelCase}.${toCamelCase(
relation.name
)}, ${toCamelCase(relation.references)}.id))`
`.leftJoin(${toCamelCase(
relation.references,
)}, eq(${tableNameCamelCase}.${toCamelCase(
relation.name,
)}, ${toCamelCase(relation.references)}.id))`,
)
: ""
}${
Expand Down Expand Up @@ -137,11 +139,11 @@ const generateDrizzleGetByIdQuery = (schema: Schema, relations: DBField[]) => {
relations.length > 0
? relations.map(
(relation) =>
`.leftJoin(${
relation.references
}, eq(${tableNameCamelCase}.${toCamelCase(
relation.name
)}, ${toCamelCase(relation.references)}.id))`
`.leftJoin(${toCamelCase(
relation.references,
)}, eq(${tableNameCamelCase}.${toCamelCase(
relation.name,
)}, ${toCamelCase(relation.references)}.id))`,
)
: ""
};
Expand All @@ -165,7 +167,10 @@ const generatePrismaGetQuery = (schema: Schema, relations: DBField[]) => {
}${belongsToUser && relations.length > 0 ? ", " : ""}${
relations.length > 0
? `include: { ${relations
.map((relation) => `${pluralize.singular(relation.references)}: true`)
.map(
(relation) =>
`${pluralize.singular(toCamelCase(relation.references))}: true`,
)
.join(", ")}}`
: ""
}});
Expand All @@ -187,14 +192,17 @@ const generatePrismaGetByIdQuery = (schema: Schema, relations: DBField[]) => {
const { id: ${tableNameSingular}Id } = ${tableNameSingular}IdSchema.parse({ id });
const ${tableNameFirstChar} = await db.${tableNameSingular}.findFirst({
where: { id: ${tableNameSingular}Id${
belongsToUser ? `, userId: session?.user.id!` : ""
}}${
relations.length > 0
? `,\n include: { ${relations
.map((relation) => `${relation.references.slice(0, -1)}: true`)
.join(", ")} }\n `
: ""
}});
belongsToUser ? `, userId: session?.user.id!` : ""
}}${
relations.length > 0
? `,\n include: { ${relations
.map(
(relation) =>
`${pluralize.singular(toCamelCase(relation.references))}: true`,
)
.join(", ")} }\n `
: ""
}});
return { ${tableNameCamelCase}: ${tableNameFirstChar} };
};
`;
Expand Down
62 changes: 31 additions & 31 deletions src/commands/generate/generators/model/schema/index.ts
Expand Up @@ -28,7 +28,7 @@ const getUsedTypes = (fields: DBField[], mappings: TypeMap) => {
return mappingFunction({ name: field.name }).split("(")[0];
})
.concat(
mappings.typeMappings["id"]({ name: "id" }).split("(")[0]
mappings.typeMappings["id"]({ name: "id" }).split("(")[0],
) as DrizzleColumnType[]; // Assuming number (int) is always used for the 'id' field
};

Expand All @@ -37,22 +37,22 @@ const getReferenceImports = (fields: DBField[]) => {
return referenceFields.map(
(field) =>
`import { ${toCamelCase(field.references)} } from "./${toCamelCase(
field.references
)}"`
field.references,
)}"`,
);
};

const getUniqueTypes = (
usedTypes: string[],
belongsToUser: boolean,
dbType: DBType
dbType: DBType,
) => {
return Array.from(
new Set(
usedTypes.concat(
belongsToUser ? [getReferenceFieldType("string")[dbType]] : []
)
)
belongsToUser ? [getReferenceFieldType("string")[dbType]] : [],
),
),
);
};

Expand All @@ -62,7 +62,7 @@ const generateImportStatement = (
mappings: TypeMap,
authType: AuthType,
dbType?: DBType,
provider?: DBProvider
provider?: DBProvider,
) => {
const { alias } = readConfigFile();
const { fields, belongsToUser, tableName } = schema;
Expand All @@ -79,7 +79,7 @@ const generateImportStatement = (
return `import { ${uniqueTypes
.join(", ")
.concat(
`, ${mappings.tableFunc}`
`, ${mappings.tableFunc}`,
)} } from "drizzle-orm/${dbType}-core";\nimport { createInsertSchema, createSelectSchema } from "drizzle-zod";\nimport { z } from "zod";\n${
referenceImports.length > 0 ? referenceImports.join("\n") : ""
}${
Expand All @@ -92,15 +92,15 @@ const generateImportStatement = (
}
import { get${tableNameCapitalised} } from "${formatFilePath(
shared.orm.servicesDir,
{ prefix: "alias", removeExtension: false }
{ prefix: "alias", removeExtension: false },
)}/${tableNameCamelCase}/queries";`;
}
if (orm === "prisma")
return `import { ${tableNameSingular}Schema } from "${alias}/zodAutoGenSchemas";
import { z } from "zod";
import { get${tableNameCapitalised} } from "${formatFilePath(
shared.orm.servicesDir,
{ prefix: "alias", removeExtension: false }
{ prefix: "alias", removeExtension: false },
)}/${tableNameCamelCase}/queries";
`;
};
Expand All @@ -110,8 +110,8 @@ const generateFieldsForSchema = (fields: DBField[], mappings: TypeMap) => {
.map(
(field) =>
` ${toCamelCase(field.name)}: ${mappings.typeMappings[field.type](
field
)}${field.notNull ? ".notNull()" : ""}`
field,
)}${field.notNull ? ".notNull()" : ""}`,
)
.join(",\n");
};
Expand All @@ -123,10 +123,10 @@ const generateIndex = (schema: Schema) => {
? `, (${tableNameCamelCase}) => {
return {
${toCamelCase(
index
index,
)}Index: uniqueIndex('${index}_idx').on(${tableNameCamelCase}.${toCamelCase(
index
)}),
index,
)}),
}
}`
: "";
Expand All @@ -135,7 +135,7 @@ const generateIndex = (schema: Schema) => {
const addUserReferenceIfBelongsToUser = (
schema: Schema,
mappings: TypeMap,
authType: AuthType
authType: AuthType,
) => {
const authSubtype = AuthSubTypeMapping[authType];
const value = schema.belongsToUser
Expand All @@ -148,7 +148,7 @@ const addUserReferenceIfBelongsToUser = (
: "";
const valueIfManaged = value.replace(
`.references(() => users.id, { onDelete: "cascade" })`,
""
"",
);
return authSubtype === "managed" ? valueIfManaged : value;
};
Expand All @@ -159,7 +159,7 @@ const generateDrizzleSchema = (
provider: DBProvider,
dbType: DBType,
zodSchemas: string,
authType: AuthType
authType: AuthType,
) => {
const { tableName, fields } = schema;
const { tableNameCamelCase } = formatTableName(tableName);
Expand All @@ -170,7 +170,7 @@ const generateDrizzleSchema = (
mappings,
authType,
dbType,
provider
provider,
);

const userGeneratedFields = generateFieldsForSchema(fields, mappings);
Expand All @@ -183,7 +183,7 @@ const generateDrizzleSchema = (
${userGeneratedFields}${addUserReferenceIfBelongsToUser(
schema,
mappings,
authType
authType,
)}
}${indexFormatted});\n`;

Expand All @@ -193,7 +193,7 @@ ${userGeneratedFields}${addUserReferenceIfBelongsToUser(
const generateIndexFields = (
schema: Schema,
relations: DBField[],
usingPlanetscale: boolean
usingPlanetscale: boolean,
): string => {
const { index, belongsToUser } = schema;
// Handle the case where index is null and there are no relations and usingPlanetscale is false
Expand All @@ -216,7 +216,7 @@ const generateIndexFields = (
// If using planetscale and there are relations, add relations to fields array
if (usingPlanetscale && relations.length > 0) {
fields = fields.concat(
relations.map((relation) => toCamelCase(relation.name))
relations.map((relation) => toCamelCase(relation.name)),
);
}

Expand All @@ -232,14 +232,14 @@ const generatePrismaSchema = (
mappings: TypeMap,
zodSchemas: string,
usingPlanetscale: boolean,
authType: AuthType
authType: AuthType,
) => {
const { tableNameSingularCapitalised, tableNameCamelCase } = formatTableName(
schema.tableName
schema.tableName,
);
const authSubtype = AuthSubTypeMapping[authType];
const relations = schema.fields.filter(
(field) => field.type === "References"
(field) => field.type === "References",
);
const prismaSchemaContent = `model ${tableNameSingularCapitalised} {
id String @id @default(cuid())
Expand All @@ -260,7 +260,7 @@ const generatePrismaSchema = (
if (schema.belongsToUser && authSubtype === "self-hosted")
addToPrismaModel(
"User",
`${tableNameCamelCase} ${tableNameSingularCapitalised}[]`
`${tableNameCamelCase} ${tableNameSingularCapitalised}[]`,
);

relations.forEach((relation) => {
Expand All @@ -269,14 +269,14 @@ const generatePrismaSchema = (
formatTableName(references);
addToPrismaModel(
singularCapitalised,
`${tableNameCamelCase} ${tableNameSingularCapitalised}[]`
`${tableNameCamelCase} ${tableNameSingularCapitalised}[]`,
);
});
const importStatement = generateImportStatement(
"prisma",
schema,
mappings,
authType
authType,
);

return `${importStatement}\n\n${zodSchemas}`;
Expand All @@ -294,7 +294,7 @@ export function generateModelContent(schema: Schema, dbType: DBType) {
provider,
dbType,
zodSchemas,
auth
auth,
);
}
if (orm === "prisma") {
Expand All @@ -303,7 +303,7 @@ export function generateModelContent(schema: Schema, dbType: DBType) {
mappings,
zodSchemas,
provider === "planetscale",
auth
auth,
);
}
}

0 comments on commit 83b4314

Please sign in to comment.