Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor code updates #183

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/commands/add/auth/lucia/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,8 +519,8 @@ export async function updateUser(

if (!result.success) {
const error = result.error.flatten().fieldErrors;
if (error.name) return { error: "Invalid name - " + error.name[0] };
if (error.email) return { error: "Invalid email - " + error.email[0] };
if (error.name) return { error: \`Invalid name - \${error.name[0]}\` };
if (error.email) return { error: \`Invalid email - \${error.email[0]}\` };
return genericError;
}

Expand Down Expand Up @@ -694,10 +694,10 @@ const generateAuthDirFiles = (
const utilsTs = `import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'

import { type Cookie } from 'lucia'
import type { Cookie } from 'lucia'

import { validateRequest } from './lucia'
import { UsernameAndPassword, authenticationSchema } from '../db/schema/auth'
import { type UsernameAndPassword, authenticationSchema } from '../db/schema/auth'

export type AuthSession = {
session: {
Expand Down Expand Up @@ -735,9 +735,9 @@ export const setAuthCookie = (cookie: Cookie) => {
cookies().set(cookie);
}

const getErrorMessage = (errors: any): string => {
const getErrorMessage = (errors: { email?: string[] | undefined; password?: string[] | undefined }): string => {
if (errors.email) return 'Invalid Email'
if (errors.password) return 'Invalid Password - ' + errors.password[0]
if (errors.password) return \`Invalid Password - \${errors.password[0]}\`
return '' // return a default error message or an empty string
}

Expand Down Expand Up @@ -814,7 +814,7 @@ export const validateRequest = cache(
const result = await lucia.validateSession(sessionId)
// next.js throws when you attempt to set cookie when rendering page
try {
if (result.session && result.session.fresh) {
if (result.session?.fresh) {
const sessionCookie = lucia.createSessionCookie(result.session.id)
cookies().set(
sessionCookie.name,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/add/auth/lucia/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export const addLucia = async () => {
removeExtension: false,
prefix: "rootPath",
}),
`import { z } from "zod";
`import type { z } from "zod";

export const authenticationSchema = z.object({
email: z.string().email().min(5).max(31),
Expand Down
6 changes: 3 additions & 3 deletions src/commands/add/auth/lucia/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ import { sessions, users } from "../db/schema/auth";
};

export const DrizzleLuciaSchema: { [k in DBType]: string } = {
pg: `import { z } from "zod";
pg: `import type { z } from "zod";
import { pgTable, timestamp, text } from "drizzle-orm/pg-core";

export const users = pgTable("user", {
Expand All @@ -99,7 +99,7 @@ export const sessions = pgTable("session", {
}).notNull()
});
`,
mysql: `import { z } from "zod";
mysql: `import type { z } from "zod";
import { mysqlTable, varchar, datetime } from "drizzle-orm/mysql-core";

export const users = mysqlTable("user", {
Expand Down Expand Up @@ -128,7 +128,7 @@ export const sessions = mysqlTable("session", {
.references(() => users.id),
expiresAt: datetime("expires_at").notNull()
});`,
sqlite: `import { z } from "zod";
sqlite: `import type { z } from "zod";
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";

export const users = sqliteTable("user", {
Expand Down
10 changes: 5 additions & 5 deletions src/commands/add/auth/shared/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const createUserSettingsComponent = () => {
return `"use client";
import UpdateNameCard from "./UpdateNameCard";
import UpdateEmailCard from "./UpdateEmailCard";
import { AuthSession } from "${formatFilePath(shared.auth.authUtils, {
import type { AuthSession } from "${formatFilePath(shared.auth.authUtils, {
prefix: "alias",
removeExtension: true,
})}";
Expand Down Expand Up @@ -58,7 +58,7 @@ export default function UpdateNameCard({ name }: { name: string }) {
});

useEffect(() => {
if (state.success == true) toast.success("Updated User");
if (state.success === true) toast.success("Updated User");
if (state.error) toast.error("Error", { description: state.error });
}, [state]);

Expand Down Expand Up @@ -161,7 +161,7 @@ export default function UpdateNameCard({ name }: { name: string }) {
});

useEffect(() => {
if (state.success == true) alert("Updated User");
if (state.success === true) alert("Updated User");
if (state.error) alert("Error");
}, [state]);

Expand Down Expand Up @@ -288,7 +288,7 @@ export default function UpdateEmailCard({ email }: { email: string }) {
});

useEffect(() => {
if (state.success == true) toast.success("Updated Email");
if (state.success === true) toast.success("Updated Email");
if (state.error) toast.error("Error", { description: state.error });
}, [state]);

Expand Down Expand Up @@ -393,7 +393,7 @@ export default function UpdateEmailCard({ email }: { email: string }) {
});

useEffect(() => {
if (state.success == true) alert("Updated User");
if (state.success === true) alert("Updated User");
if (state.error) alert("Error");
}, [state]);

Expand Down
2 changes: 1 addition & 1 deletion src/commands/add/componentLib/shadcn-ui/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ const generateThemeProvider = () => {

import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";
import type { ThemeProviderProps } from "next-themes/dist/types";

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
Expand Down
3 changes: 2 additions & 1 deletion src/commands/add/misc/defaultStyles/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ const landingPage = `/**
* Documentation: https://v0.dev/docs#integrating-generated-code-into-your-nextjs-app
*/
import Link from "next/link";
import type { JSX,SVGProps } from "react"

export default function LandingPage() {
return (
Expand Down Expand Up @@ -359,7 +360,7 @@ export default function LandingPage() {
);
}

function MountainIcon(props: any) {
function MountainIcon(props: JSX.IntrinsicAttributes & SVGProps<SVGSVGElement>) {
return (
<svg
{...props}
Expand Down
10 changes: 5 additions & 5 deletions src/commands/add/misc/navbar/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export default function Page() {

const generateNavConfig = () => {
const { componentLib, auth } = readConfigFile();
return `import { SidebarLink } from "${formatFilePath(
return `import type { SidebarLink } from "${formatFilePath(
"components/SidebarItems",
{
prefix: "alias",
Expand Down Expand Up @@ -210,7 +210,7 @@ const generateSidebarItemsTsx = () => {
import Link from "next/link";
import { usePathname } from "next/navigation";

import { LucideIcon } from "lucide-react";
import type { LucideIcon } from "lucide-react";

${
componentLib === "shadcn-ui"
Expand Down Expand Up @@ -260,7 +260,7 @@ const SidebarLinkGroup = ({
border?: boolean;
}) => {
const fullPathname = usePathname();
const pathname = "/" + fullPathname.split("/")[1];
const pathname = \`/\${fullPathname.split("/")[1]}\`;

return (
<div className={border ? "border-border border-t my-8 pt-4" : ""}>
Expand Down Expand Up @@ -347,7 +347,7 @@ import SidebarItems from "./SidebarItems";${
: null
}

import { AuthSession, getUserAuth } from "${formatFilePath(
import { type AuthSession, getUserAuth } from "${formatFilePath(
shared.auth.authUtils,
{
prefix: "alias",
Expand Down Expand Up @@ -378,7 +378,7 @@ const UserDetails = ({ session }: { session: AuthSession }) => {
if (session.session === null) return null;
const { user } = session.session;

if (!user?.name || user.name.length == 0) return null;
if (!user?.name || user.name.length === 0) return null;

return (
<Link href="/account">
Expand Down
4 changes: 2 additions & 2 deletions src/commands/add/misc/resend/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { emailSchema } from "${formatFilePath(resend.emailUtils, {
removeExtension: true,
})}";
import { useRef, useState } from "react";
import { z } from "zod";
import type { z } from "zod";

type FormInput = z.infer<typeof emailSchema>;
type Errors = { [K in keyof FormInput]: string[] };
Expand Down Expand Up @@ -220,7 +220,7 @@ export const resend = new Resend(env.RESEND_API_KEY);
};

const generateEmailUtilsTs = () => {
return `import { z } from "zod";
return `import type { z } from "zod";

export const emailSchema = z.object({
name: z.string().min(3),
Expand Down
15 changes: 8 additions & 7 deletions src/commands/add/misc/trpc/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
`;
const { trpc } = getFilePaths();
return `import { initTRPC, TRPCError } from "@trpc/server";
import { Context } from "${formatFilePath(trpc.trpcContext, {
import type { Context } from "${formatFilePath(trpc.trpcContext, {
prefix: "alias",
removeExtension: true,
})}";
Expand Down Expand Up @@ -121,7 +121,7 @@ export const apiTrpcRouteTs = () => {
const { trpc, shared } = getFilePaths();
return `import { fetchRequestHandler } from "@trpc/server/adapters/fetch";

import { NextRequest } from "next/server";
import type { NextRequest } from "next/server";
import { appRouter } from "${formatFilePath(trpc.rootRouter, {
prefix: "alias",
removeExtension: true,
Expand Down Expand Up @@ -166,7 +166,7 @@ export const libTrpcClientTs = () => {
const { trpc } = getFilePaths();
return `import { createTRPCReact } from "@trpc/react-query";

import { type AppRouter } from "${formatFilePath(trpc.rootRouter, {
import type { AppRouter } from "${formatFilePath(trpc.rootRouter, {
prefix: "alias",
removeExtension: true,
})}";
Expand All @@ -180,7 +180,8 @@ export const libTrpcProviderTsx = () => {

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { loggerLink, unstable_httpBatchStreamLink } from "@trpc/client";
import React, { useState } from "react";
import type React from "react";
import { useState } from "react";

import { trpc } from "./client";
import { getUrl } from "./utils";
Expand Down Expand Up @@ -273,7 +274,7 @@ import {
TRPCClientError,
} from "@trpc/client";
import { callProcedure } from "@trpc/server";
import { type TRPCErrorResponse } from "@trpc/server/rpc";
import type { TRPCErrorResponse } from "@trpc/server/rpc";
import { observable } from "@trpc/server/observable";

import { cache } from "react";
Expand Down Expand Up @@ -386,15 +387,15 @@ export const libTrpcUtilsTs = () => {
}

export function getUrl() {
return getBaseUrl() + "/api/trpc";
return \`\${getBaseUrl()}/api/trpc\`;
}`;
};

export const libTrpcApiTsBatchLink = () => {
const { trpc } = getFilePaths();

return `import { cookies } from "next/headers";
import { type AppRouter } from "${formatFilePath(trpc.rootRouter, {
import type { AppRouter } from "${formatFilePath(trpc.rootRouter, {
prefix: "alias",
removeExtension: true,
})}";
Expand Down
2 changes: 1 addition & 1 deletion src/commands/add/orm/drizzle/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,7 @@ const generateEnvMjs = (
blank = false
) => {
return `import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";${
import type { z } from "zod";${
preferredPackageManager !== "bun" && ormType === "drizzle"
? '\nimport "dotenv/config";'
: ""
Expand Down
2 changes: 1 addition & 1 deletion src/commands/add/orm/prisma/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ if (process.env.NODE_ENV !== "production") global.db = db;
export const generatePrismaComputerModel = () => {
const { alias } = readConfigFile();
return `import { computerSchema } from "${alias}/zodAutoGenSchemas";
import { z } from "zod";
import type { z } from "zod";

export const insertComputerSchema = computerSchema;
export const insertComputerParams = computerSchema.omit({
Expand Down
2 changes: 1 addition & 1 deletion src/commands/generate/generators/apiRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const generateRouteContent = (schema: Schema, driver: DBType) => {

const template = `import { NextResponse } from "next/server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import type { z } from "zod";

import {
create${tableNameSingularCapitalised},
Expand Down
6 changes: 3 additions & 3 deletions src/commands/generate/generators/model/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const generateImportStatement = (
.join(", ")
.concat(
`, ${mappings.tableFunc}`
)}${schema.index ? ", uniqueIndex" : ""} } from "drizzle-orm/${dbType}-core";\nimport { createInsertSchema, createSelectSchema } from "drizzle-zod";\nimport { z } from "zod";\n${
)}${schema.index ? ", uniqueIndex" : ""} } from "drizzle-orm/${dbType}-core";\nimport { createInsertSchema, createSelectSchema } from "drizzle-zod";\nimport type { z } from "zod";\n${
referenceImports.length > 0 ? referenceImports.join("\n") : ""
}${
belongsToUser && provider !== "planetscale" && authSubType !== "managed"
Expand All @@ -96,7 +96,7 @@ const generateImportStatement = (
})}";`
: ""
}
import { type get${tableNameCapitalised} } from "${formatFilePath(
import type { get${tableNameCapitalised} } from "${formatFilePath(
shared.orm.servicesDir,
{ prefix: "alias", removeExtension: false }
)}/${tableNameCamelCase}/queries";
Expand All @@ -111,7 +111,7 @@ import { nanoid${
}
if (orm === "prisma")
return `import { ${tableNameSingular}Schema } from "${alias}/zodAutoGenSchemas";
import { z } from "zod";${
import type { z } from "zod";${
schema.includeTimestamps
? `\nimport { timestamps } from "${formatFilePath("lib/utils", {
prefix: "alias",
Expand Down
16 changes: 15 additions & 1 deletion src/commands/generate/generators/views-with-server-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,7 @@ const createFormComponent = (schema: Schema) => {
...new Set(schema.fields.map((field) => field.type)),
] as ColumnType[];

return `import { z } from "zod";
return `import type { z } from "zod";

import { useState, useTransition } from "react";
import { useFormStatus } from "react-dom";
Expand Down Expand Up @@ -933,6 +933,20 @@ const ${tableNameSingularCapitalised}Form = ({${
}
};

const onError = (
action: Action,
data?: { error: string; values: ${tableNameSingularCapitalised} },
) => {
const failed = Boolean(data?.error);
if (failed) {
openModal && openModal(data?.values);
toast.error(\`Failed to \${action}\`, {
description: data?.error ?? "Error",
});
}
return
};

const handleSubmit = async (data: FormData) => {
setErrors(null);

Expand Down
Loading