Skip to content

Commit

Permalink
added usebackpath abstraction for post delete action
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoalbanese committed Feb 5, 2024
1 parent eedf3d2 commit 7e9cc7e
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 20 deletions.
36 changes: 26 additions & 10 deletions src/commands/generate/generators/model/queries/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,11 @@ const generatePrismaGetByIdQuery = (schema: Schema, relations: DBField[]) => {
`;
};

type TJoin = {
name: string;
type: "relation" | "child";
nameCapitalised?: string;
};
const generatePrismaGetByIdQueryWithChildren = (
schema: ExtendedSchema,
relations: DBField[]
Expand All @@ -354,24 +359,28 @@ const generatePrismaGetByIdQueryWithChildren = (

const { tableName, belongsToUser, children } = schema;

const relationsTableNames = relations.map(
(r) => formatTableName(r.references).tableNameSingular
);
const childrenTableNames = children.map(
(c) => formatTableName(c.tableName).tableNameCamelCase
);
const relationsTableNames: TJoin[] = relations.map((r) => ({
name: formatTableName(r.references).tableNameSingular,
type: "relation",
}));
const childrenTableNames: TJoin[] = children.map((c) => ({
name: formatTableName(c.tableName).tableNameCamelCase,
nameCapitalised: formatTableName(c.tableName).tableNameCapitalised,
type: "child",
}));
const joins = Array.from(
new Set([...relationsTableNames, ...childrenTableNames])
);

const {
tableNameSingular,
tableNameCamelCase,
tableNameSingularCapitalised,
tableNameFirstChar,
} = formatTableName(tableName);
const getAuth = generateAuthCheck(schema.belongsToUser);
return `export const get${tableNameSingularCapitalised}ByIdWith${childrenTableNames
.map((c) => formatTableName(c).tableNameCapitalised)
.map((c) => c.nameCapitalised)
.join("And")} = async (id: ${tableNameSingularCapitalised}Id) => {${getAuth}
const { id: ${tableNameSingular}Id } = ${tableNameSingular}IdSchema.parse({ id });
const ${tableNameFirstChar} = await db.${tableNameSingular}.findFirst({
Expand All @@ -380,21 +389,28 @@ const generatePrismaGetByIdQueryWithChildren = (
}}${
joins.length > 0
? `,\n include: { ${joins
.map((j) => `${j}: { include: {${tableNameSingular}: true } }`)
.map(
(j) =>
`${j.name}: { include: {${
j.type === "child" ? tableNameSingular : tableNameCamelCase
}: true } }`
)
.join(", ")} }\n `
: ""
}});
${
childrenTableNames.length > 0
? `if (${tableNameFirstChar} === null) return { ${tableNameSingular}: null };
const { ${joins
.map((j) => `${j}`)
.map((j) => `${j.name}`)
.join(", ")}, ...${tableNameSingular} } = ${tableNameFirstChar};
`
: ""
}
return { ${tableNameSingular}${
joins.length > 0 ? `, ${joins.map((j) => `${j}:${j}`).join(", ")}` : ""
joins.length > 0
? `, ${joins.map((j) => `${j.name}:${j.name}`).join(", ")}`
: ""
} };
};
`;
Expand Down
2 changes: 1 addition & 1 deletion src/commands/generate/generators/model/queries/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const generateQueryContent = (schema: ExtendedSchema, orm: ORMType) => {
const getQuery = generateQueries[orm].get(schema, relations);
const getByIdQuery = generateQueries[orm].getById(schema, relations);
const getByIdWithChildren =
schema.children.length > 0
schema.children && schema.children.length > 0
? generateQueries[orm].getByIdWithChildren(schema, relations)
: "";

Expand Down
29 changes: 20 additions & 9 deletions src/commands/generate/generators/views-with-server-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,11 @@ import { Label } from "${formatFilePath(`components/ui/label`, {
prefix: "alias",
removeExtension: false,
})}";
import { useBackPath } from "${formatFilePath(`components/shared/BackButton`, {
prefix: "alias",
removeExtension: false,
})}";
${uniqueFieldTypes
.map((field) => createFormInputComponentImports(field))
.join("\n")}
Expand Down Expand Up @@ -911,6 +916,8 @@ const ${tableNameSingularCapitalised}Form = ({${
const [pending, startMutation] = useTransition();
const router = useRouter();
const backpath = useBackPath("${tableNameKebabCase}");
const onSuccess = (
action: Action,
Expand Down Expand Up @@ -1029,7 +1036,7 @@ const ${tableNameSingularCapitalised}Form = ({${
onSuccess("delete", error ? errorFormatted : undefined);
});
router.push("/${tableNameKebabCase}");
router.push(backpath);
}}
>
Delet{isDeleting ? "ing..." : "e"}
Expand Down Expand Up @@ -1156,19 +1163,24 @@ import { Button } from "${formatFilePath("components/ui/button", {
prefix: "alias",
})}";
export default function BackButton({
currentResource,
}: {
/* must be in kebab-case */
currentResource: string;
}) {
export function useBackPath(currentResource: string) {
const pathname = usePathname();
const segmentCount = pathname.slice(1).split("/");
const backPath =
segmentCount.length > 2
? pathname.slice(0, pathname.indexOf(currentResource) - 1)
: pathname.slice(0, pathname.indexOf(segmentCount[1]));
return backPath;
}
export function BackButton({
currentResource,
}: {
/* must be in kebab-case */
currentResource: string;
}) {
const backPath = useBackPath(currentResource);
return (
<Button variant={"ghost"} asChild>
<Link href={backPath}>
Expand All @@ -1177,7 +1189,6 @@ export default function BackButton({
</Button>
);
}
`;
createFile(bbPath, bbContents);
}
Expand Down Expand Up @@ -1425,7 +1436,7 @@ ${
: ""
}
import BackButton from "${formatFilePath("components/shared/BackButton", {
import { BackButton } from "${formatFilePath("components/shared/BackButton", {
prefix: "alias",
removeExtension: false,
})}";
Expand Down
1 change: 1 addition & 0 deletions src/commands/generate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ async function getSchema(
resourceType: TResource[]
): Promise<Schema> {
const baseSchema = await promptUserForSchema(config, resourceType);
if (resourceType.includes("views_and_components_trpc")) return baseSchema;
return await addChildSchemaToParent(config, resourceType, baseSchema);
}

Expand Down

0 comments on commit 7e9cc7e

Please sign in to comment.