Knox
Knox
Explore posts from servers
TTCTheo's Typesafe Cult
Created by Knox on 6/24/2024 in #questions
Migrate react-scripts to vite
I have a project using react-scripts 4 with a proxy-dev-server needed to start the app where I have:
const express = require('express')
const app = express()
const { createProxyMiddleware } = require('http-proxy-middleware')
const fs = require('fs')
require('dotenv').config()

const wsProxy = createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000',
ws: true
})

app.use(
'/api/v2',
createProxyMiddleware({
secure: true,
changeOrigin: true,
target: {
protocol: 'https:',
host: '127.0.0.1',
port: 8443,
pfx: fs.readFileSync(process.env.PROXY_CERT_PATH),
passphrase: process.env.PROXY_CERT_PASSPHRASE
}
})
)

app.use('/sockjs-node', wsProxy)

app.use(
'/',
createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000'
})
)

const server = app.listen(3001)

server.on('upgrade', wsProxy.upgrade)
const express = require('express')
const app = express()
const { createProxyMiddleware } = require('http-proxy-middleware')
const fs = require('fs')
require('dotenv').config()

const wsProxy = createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000',
ws: true
})

app.use(
'/api/v2',
createProxyMiddleware({
secure: true,
changeOrigin: true,
target: {
protocol: 'https:',
host: '127.0.0.1',
port: 8443,
pfx: fs.readFileSync(process.env.PROXY_CERT_PATH),
passphrase: process.env.PROXY_CERT_PASSPHRASE
}
})
)

app.use('/sockjs-node', wsProxy)

app.use(
'/',
createProxyMiddleware({
changeOrigin: true,
target: 'http://localhost:3000'
})
)

const server = app.listen(3001)

server.on('upgrade', wsProxy.upgrade)
And I'm migrating the project to use vite. I have almost everything done, can start the app but can't start the session My new vite.config.ts looks like this https://gist.github.com/FACorreiaa/3c87607cb52ee6a52d332b5b2a0875f9 And from the examples I saw I need to start my proxy and vite concurrently:
{
"dev": "concurrently -k \"npm run proxy-dev-server\" \"npm run react:start\"",
"proxy-dev-server": "node proxy-dev-server.js",
"react:start": "vite --port 3000 --host 127.0.0.1",
{
"dev": "concurrently -k \"npm run proxy-dev-server\" \"npm run react:start\"",
"proxy-dev-server": "node proxy-dev-server.js",
"react:start": "vite --port 3000 --host 127.0.0.1",
My server endpoint responds with json https://127.0.0.1:8443/api/v2/system/status status: "operational" But when I try to start my session I get:
useUserSession.ts:10


GET http://localhost:3001/api/v2/session 404 (Not Found)
useUserSession.ts:10


GET http://localhost:3001/api/v2/session 404 (Not Found)
If I go back on the react-scripts configs everything works fine tho. Anyone has any clue on what I might be missing on the vite part ?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 5/8/2024 in #questions
Migrating react-query v3 to tanstack-query v4
Im almost finishing this migration process
const getChanges = async (): Promise<Changeset | undefined> => {
try {
const { data } = await Axios.get<Changeset | undefined>('/changeset')
return data
} catch {
return undefined
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}

export default useChanges
const getChanges = async (): Promise<Changeset | undefined> => {
try {
const { data } = await Axios.get<Changeset | undefined>('/changeset')
return data
} catch {
return undefined
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}

export default useChanges
Right now the problem im having is on the getChanges function:
Argument of type '() => Promise<Changeset | undefined>' is not assignable to parameter of type 'QueryFunction<Changeset, string[], any>'.
Argument of type '() => Promise<Changeset | undefined>' is not assignable to parameter of type 'QueryFunction<Changeset, string[], any>'.
Deleting the undefined value solves this error highlighting but the fetch of the data fails.
const getChanges = async (): Promise<Changeset> => {
try {
const { data } = await Axios.get<Changeset>('/changeset')
return data
} catch (error) {
throw new Error('Failed to fetch changeset')
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}
const getChanges = async (): Promise<Changeset> => {
try {
const { data } = await Axios.get<Changeset>('/changeset')
return data
} catch (error) {
throw new Error('Failed to fetch changeset')
}
}

const useChanges = <T = Changeset | undefined>(
options?: UseQueryOptions<Changeset | undefined, AxiosError, T>
) => {
return useQuery(['changes'], getChanges, {
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
...options
})
}
Missing queryFn for queryKey 'undefined' index.js:1191
XHRGET
http://localhost:3001/api/v2/changeset
[HTTP/1.1 404 Not Found 74ms]

Error: Failed to fetch changeset
Missing queryFn for queryKey 'undefined' index.js:1191
XHRGET
http://localhost:3001/api/v2/changeset
[HTTP/1.1 404 Not Found 74ms]

Error: Failed to fetch changeset
Am I missing something ?
5 replies
TTCTheo's Typesafe Cult
Created by Knox on 4/10/2024 in #questions
React Table v7 Sorting
I have a question regarding react-table v7, its not possible to have server side sorting with the table doing the handle the sorting, right ? From what I see on the examples, if I have client side sort I can have the table take care of it, but If I want it to be server side I need to handle all the logic including function to sort, icons (ascend, descent) etc. Right now I have server side pagination working but the sorting is still being handled by the table and what happens is that the sorting is only applied on the page itself (so for the first 40 elements, being 40 my limit). Im pretty sure I need to do all the logic, I just wanted to avoid having extra work and style everything.
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/5/2024 in #questions
React query useInfiniteQuery (v3) and react table (v7) for server side pagination
Anyone has every connected react-query v3 with react-table v7 ? Im trying to implement a server side paginator with infinite scrolling doing:
const {
data: devicesData,
isFetching,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
isFetchingNextPage,
hasPreviousPage,
isFetchingPreviousPage
} = useDevices({}, pageNumber, pageSize)
const {
data: devicesData,
isFetching,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
isFetchingNextPage,
hasPreviousPage,
isFetchingPreviousPage
} = useDevices({}, pageNumber, pageSize)
And everything seems ok if I implement custom button paginators like:
<button onClick={() => gotoPage(0)} disabled={!hasPreviousPage || isFetchingPreviousPage}>
{'<<'}
</button>{' '}
<button
onClick={() => previousPage()}
disabled={!hasPreviousPage || isFetchingPreviousPage}
>
{'<'}
</button>{' '}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
{'>'}
</button>{' '}
<button
onClick={() => gotoPage(pageOptions.length - 1)}
disabled={!hasNextPage || isFetchingNextPage}
>
{'>>'}
<button onClick={() => gotoPage(0)} disabled={!hasPreviousPage || isFetchingPreviousPage}>
{'<<'}
</button>{' '}
<button
onClick={() => previousPage()}
disabled={!hasPreviousPage || isFetchingPreviousPage}
>
{'<'}
</button>{' '}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
{'>'}
</button>{' '}
<button
onClick={() => gotoPage(pageOptions.length - 1)}
disabled={!hasNextPage || isFetchingNextPage}
>
{'>>'}
but have weird behavior on the custom table paginator that react-table renders:
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage
// Get the state from the instance
} = useTable(
{
//@ts-ignore
columns,

nextPage: () => setPageNumber(pageNumber + 1),
previousPage: () => setPageNumber(pageNumber - 1),
//nextPage: fetchNextPage(),
//previousPage: fetchPreviousPage(),
data: devicesByStatus,
state: {
pageNumber,
pageSize
},
manualPagination: true // Set to false to let useTable handle pagination
},
usePagination
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage
// Get the state from the instance
} = useTable(
{
//@ts-ignore
columns,

nextPage: () => setPageNumber(pageNumber + 1),
previousPage: () => setPageNumber(pageNumber - 1),
//nextPage: fetchNextPage(),
//previousPage: fetchPreviousPage(),
data: devicesByStatus,
state: {
pageNumber,
pageSize
},
manualPagination: true // Set to false to let useTable handle pagination
},
usePagination
)
8 replies
TTCTheo's Typesafe Cult
Created by Knox on 2/26/2024 in #questions
Cancel query when query value reaches to 0
Im making a query that returns me a set of values and that value with decrease over time till it reaches 0. I need to fetch every 100ms the query but I want to be able to cancel the query when outdatedObjects reaches 0.
const useDeviceStatus = (options?: UseQueryOptions<any, AxiosError>) => {
const queryData = useQuery(
'device',
async () => {
const { data } = await Axios.get<Device[]>('/system/status/info')
return data
},
{
enabled: true,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
refetchInterval: 100,
...options
}
)
return queryData
}

export default useDeviceStatus
const useDeviceStatus = (options?: UseQueryOptions<any, AxiosError>) => {
const queryData = useQuery(
'device',
async () => {
const { data } = await Axios.get<Device[]>('/system/status/info')
return data
},
{
enabled: true,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: Infinity,
refetchInterval: 100,
...options
}
)
return queryData
}

export default useDeviceStatus
export default function LinearWithValueLabel() {
const [progress, setProgress] = React.useState(1)
const { status, data: deviceStatus, error, isFetching } = useDeviceStatus()
const outdatedObjects = deviceStatus?.info.outdated_objects_count
const total_objects_count = deviceStatus?.info.total_objects_count
const queryClient = useQueryClient()

React.useEffect(() => {
if (!outdatedObjects || outdatedObjects === 0) {
setProgress(0)
return
}
if (outdatedObjects < 1) {
queryClient.setQueryData('device', null)
queryClient.cancelQueries('device')

return
}

const percentage = ((total_objects_count - outdatedObjects) / total_objects_count) * 100

setProgress(percentage)
}, [outdatedObjects])



return (
<>
{outdatedObjects > 0 && (
<Box display="flex" alignItems="center" width={'600px'}>
<LinearProgress
variant="determinate"
value={progress}
sx={{ width: '100%', padding: '2px', borderRadius: '5px', marginRight: '10px' }}
/>

{`${total_objects_count} ` +
'of ' +
`${outdatedObjects}`}

</Box>
)}
</>
)
}
export default function LinearWithValueLabel() {
const [progress, setProgress] = React.useState(1)
const { status, data: deviceStatus, error, isFetching } = useDeviceStatus()
const outdatedObjects = deviceStatus?.info.outdated_objects_count
const total_objects_count = deviceStatus?.info.total_objects_count
const queryClient = useQueryClient()

React.useEffect(() => {
if (!outdatedObjects || outdatedObjects === 0) {
setProgress(0)
return
}
if (outdatedObjects < 1) {
queryClient.setQueryData('device', null)
queryClient.cancelQueries('device')

return
}

const percentage = ((total_objects_count - outdatedObjects) / total_objects_count) * 100

setProgress(percentage)
}, [outdatedObjects])



return (
<>
{outdatedObjects > 0 && (
<Box display="flex" alignItems="center" width={'600px'}>
<LinearProgress
variant="determinate"
value={progress}
sx={{ width: '100%', padding: '2px', borderRadius: '5px', marginRight: '10px' }}
/>

{`${total_objects_count} ` +
'of ' +
`${outdatedObjects}`}

</Box>
)}
</>
)
}
3 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/20/2023 in #questions
Open id view content from Tanstack Table with Tanstack Router
Anyone has any tip how I can render a new view in the current page of a selected item ? So im using tanstack table, query and router and if I want to open a new page when clicking an item and receiving that Item id, everything works wonderfully. But my idea is to have a table and open a view next to it instead of on a new url page.
<RouterLink
to="/page/$id"
params={{ id: props.id }}
<RouterLink
to="/page/$id"
params={{ id: props.id }}
This open a new page inside the id with the router perfectly. But what if I want just to open a new component or view inside the same page ? Anyone has a tip for this ? Any tip appreciated.
41 replies
TTCTheo's Typesafe Cult
Created by Knox on 6/5/2023 in #questions
Image component not displaying images
Hey. So using NExtJS with the app directory, I have a card component with
<Image
src={'/images/cover.jpeg'}
alt="back"
className="front"
width={500}
height={500}
priority
onClick={handleClick}
/>
<Image
src={card.src}
alt="card image"
className="front"
width={500}
height={500}
priority
/>
<Image
src={'/images/cover.jpeg'}
alt="back"
className="front"
width={500}
height={500}
priority
onClick={handleClick}
/>
<Image
src={card.src}
alt="card image"
className="front"
width={500}
height={500}
priority
/>
Where the source of the card is this object:
const cardImages = [
{ src: '/images/hiruma.jpg', matched: false },
{ src: '/images/ikki.jpg', matched: false },
{ src: '/images/ippo.jpg', matched: false },
{ src: '/images/kongo.jpg', matched: false },
{ src: '/images/kusanagi.jpg', matched: false },
{ src: '/images/luffy.jpg', matched: false },
{ src: '/images/taiga.jpg', matched: false },
{ src: '/images/takamura.jpg', matched: false },
{ src: '/images/yoko.jpg', matched: false },
];
const cardImages = [
{ src: '/images/hiruma.jpg', matched: false },
{ src: '/images/ikki.jpg', matched: false },
{ src: '/images/ippo.jpg', matched: false },
{ src: '/images/kongo.jpg', matched: false },
{ src: '/images/kusanagi.jpg', matched: false },
{ src: '/images/luffy.jpg', matched: false },
{ src: '/images/taiga.jpg', matched: false },
{ src: '/images/takamura.jpg', matched: false },
{ src: '/images/yoko.jpg', matched: false },
];
Images is inside the public folder. Any tip on why the images aren't being rendered ?
3 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/29/2023 in #questions
Vite config with playwright-ct
on the project im working we are using absolute paths so.. ~/folder/to/path And im currently having this error:
[vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
Error: [vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external
[vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
Error: [vite]: Rollup failed to resolve import "~/shared/components" from "playwright/index.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external
` Ive tried going through the simplest steps and following the documentation but so far nothing works when I run the tests. This is my vite config (sorry, too much code) https://pastebin.com/QtAGwZm1 This is my playwright-config: https://pastebin.com/PQ9TyLZD Any tip please?
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/27/2023 in #questions
Jotai migration from v1 to v2
Im trying to create an hook with useHydrateAtoms to reuse in different components:
import type { WritableAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
import type { ReactNode } from "react";

type AnyWritableAtom = WritableAtom<unknown, Array<any>, any>;

type Props = {
initialValues: Iterable<readonly [AnyWritableAtom, unknown]>;
children: ReactNode;
};
export const HydrateAtoms = (props: Props) => {
useHydrateAtoms(props.initialValues);
return props.children
};
import type { WritableAtom } from "jotai";
import { useHydrateAtoms } from "jotai/utils";
import type { ReactNode } from "react";

type AnyWritableAtom = WritableAtom<unknown, Array<any>, any>;

type Props = {
initialValues: Iterable<readonly [AnyWritableAtom, unknown]>;
children: ReactNode;
};
export const HydrateAtoms = (props: Props) => {
useHydrateAtoms(props.initialValues);
return props.children
};
And when using it on the component
type Props = {
things: number;
children: ReactNode;
};

return (
<Provider>
<HydrateAtoms initialValues={[[value1, value2]]}>
{props.children}
</HydrateAtoms>
</Provider>
);
type Props = {
things: number;
children: ReactNode;
};

return (
<Provider>
<HydrateAtoms initialValues={[[value1, value2]]}>
{props.children}
</HydrateAtoms>
</Provider>
);
Im getting this error:
'HydrateAtoms' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element.
Type 'undefined' is not assignable to type 'Element | null'.
'HydrateAtoms' cannot be used as a JSX component.
Its return type 'ReactNode' is not a valid JSX element.
Type 'undefined' is not assignable to type 'Element | null'.
Any tip?
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 3/21/2023 in #questions
Vite config with absolute paths
Im trying to make an e2e test for my components and im using absolute paths like
import { component } from "~/shared/component/test";
import { component } from "~/shared/component/test";
On my vite config I have this alias
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
},
},
resolve: {
alias: {
"~": path.resolve(__dirname, "src"),
},
},
And yet while running the test for a specific component i'm getting an error related to this absolute paths
Error: [vite]: Rollup failed to resolve import "~/types/sidebar" from "src/shared/components/sidebar/Drawer.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
Error: [vite]: Rollup failed to resolve import "~/types/sidebar" from "src/shared/components/sidebar/Drawer.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
Any idea ?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/31/2022 in #questions
Get session data inside a mutation
Hello. So im trying to create a profile inside a user that is already logged in. So the flow is Create User => Login => Create User Profile Inside the app. My Models:
model User {
id String @id @default(cuid())
email String @unique
username String @unique
password String
emailVerified DateTime?
profile Profile?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
deletedAt DateTime @default(now())
role Role @default(USER)
}

model Profile {
id String @id @default(cuid())
bio String?
profession String?
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
first_name String?
last_name String?
gender Gender
}
model User {
id String @id @default(cuid())
email String @unique
username String @unique
password String
emailVerified DateTime?
profile Profile?
accounts Account[]
sessions Session[]
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
deletedAt DateTime @default(now())
role Role @default(USER)
}

model Profile {
id String @id @default(cuid())
bio String?
profession String?
image String?
user User @relation(fields: [userId], references: [id])
userId String @unique
first_name String?
last_name String?
gender Gender
}
createProfileSchema: publicProcedure
.input(createProfileSchema)
.mutation(async ({ ctx, input }) => {
try {
const session = await getSession({ ctx.session });
const { bio, profession, image, first_name, last_name, gender } = input;
return await ctx.prisma.profile.create({
data: {
bio,
profession,
image,
first_name,
last_name,
gender,
user: { connect: { email: session.data.user.email } },
},
});
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: error,
});
}
}),
createProfileSchema: publicProcedure
.input(createProfileSchema)
.mutation(async ({ ctx, input }) => {
try {
const session = await getSession({ ctx.session });
const { bio, profession, image, first_name, last_name, gender } = input;
return await ctx.prisma.profile.create({
data: {
bio,
profession,
image,
first_name,
last_name,
gender,
user: { connect: { email: session.data.user.email } },
},
});
} catch (error) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause: error,
});
}
}),
Im failing to understand how do I get the session that is logged .. or do I even need it ?
19 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/13/2022 in #questions
Credentials Provider session always return null
So im trying to make the login page work with email and password from the DB and when i click to submit the values im always having the session as null. This is what im doing:
CredentialsProvider({
name: "Credentials",
credentials: {},
async authorize(credentials: any) {
//check user
const user: any = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});

if (!user) {
throw new Error("No user found");
}
console.log("user credentials", user);
const checkPassword = await compare(
credentials.password,
user?.password
);
console.log("user?.password", user?.password);

if (!checkPassword || user.email !== credentials.email) {
throw new Error("Password or Email dont match");
}

return user;
},
}),
],
// Include user.id on session
callbacks: {
session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
return session;
},
},
session: {
strategy: "jwt",
},
},
jwt: {
secret: "test",
},
secret: "test",
// pages: {
// signIn: "/",
// newUser: "/signin",

// signOut: "/signout",
// error: '/error'
// },
CredentialsProvider({
name: "Credentials",
credentials: {},
async authorize(credentials: any) {
//check user
const user: any = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});

if (!user) {
throw new Error("No user found");
}
console.log("user credentials", user);
const checkPassword = await compare(
credentials.password,
user?.password
);
console.log("user?.password", user?.password);

if (!checkPassword || user.email !== credentials.email) {
throw new Error("Password or Email dont match");
}

return user;
},
}),
],
// Include user.id on session
callbacks: {
session({ session, user }) {
if (session.user) {
session.user.id = user.id;
}
return session;
},
},
session: {
strategy: "jwt",
},
},
jwt: {
secret: "test",
},
secret: "test",
// pages: {
// signIn: "/",
// newUser: "/signin",

// signOut: "/signout",
// error: '/error'
// },
So on my signin page i invoke the signIn method:
async function onSubmitLoginValues(values: LoginValuesProps): Promise<any> {
const result = await signIn("credentials", {
email: values?.email,
password: values?.password,
redirect: false,
callbackUrl: "/",
});
console.log("result", result);
if (result?.ok) router.push("/");
return result;
}
async function onSubmitLoginValues(values: LoginValuesProps): Promise<any> {
const result = await signIn("credentials", {
email: values?.email,
password: values?.password,
redirect: false,
callbackUrl: "/",
});
console.log("result", result);
if (result?.ok) router.push("/");
return result;
}
result returns:
error: null
ok: true
status: 200
url: "http://localhost:3000/"
error: null
ok: true
status: 200
url: "http://localhost:3000/"
5 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/10/2022 in #questions
Good idea to mix prisma and trpc on the [...nextauth].ts file or should call a function from
So I have something like this:
CredentialsProvider({
name: "credentials",
credentials: {
email: {
label: "email",
type: "text",
placeholder: "[email protected]",
},
password: {
label: "password",
type: "password",
},
},
authorize: async (credentials: any) => {
const user = await prisma.user.findFirst({
where: {
email: credentials.email,
password: credentials.password,
},
});

if (user !== null) {
return user;
} else {
throw new Error(
"User does not exists. Please make sure you insert the correct email & password."
);
}
},
}),
],
pages: {
signIn: "/signin",
}
CredentialsProvider({
name: "credentials",
credentials: {
email: {
label: "email",
type: "text",
placeholder: "[email protected]",
},
password: {
label: "password",
type: "password",
},
},
authorize: async (credentials: any) => {
const user = await prisma.user.findFirst({
where: {
email: credentials.email,
password: credentials.password,
},
});

if (user !== null) {
return user;
} else {
throw new Error(
"User does not exists. Please make sure you insert the correct email & password."
);
}
},
}),
],
pages: {
signIn: "/signin",
}
Its my first time using NextAuth and im thinking if doing something like this inside this file is a good idea or if this logic should be inside trpc method ? Can anyone give me any tip / idea please?
2 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/8/2022 in #questions
i18next bold strings
Anyone has a better (working) solution for this ?
message={i18n.t(
'member-label:form.designConfig.highContrastTooltipMessage',
{ firstScore: `<strong>${3}</strong>`, secondScore, thirdScore },
)}
message={i18n.t(
'member-label:form.designConfig.highContrastTooltipMessage',
{ firstScore: `<strong>${3}</strong>`, secondScore, thirdScore },
)}
I basically want to pass the firstScore as bold but its not working this way or on the string itself
<strong>{{ firstScore }}</strong>
<strong>{{ firstScore }}</strong>
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/6/2022 in #questions
Sort imports
So using the create-t3-app im using the https://www.npmjs.com/package/eslint-plugin-simple-import-sort lib to sort my exports because it freaks me out to have these imports unsorted. And i extended my eslint config as follows:
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "simple-import-sort"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"rules": {
"@typescript-eslint/consistent-type-imports": "error",
"simple-import-sort/imports": [
"error",
{
"groups": [
// Packages `react` related packages come first.
["^react", "^@?\\w"],
// Internal packages.
["^(@|components)(/.*|$)"],
// Side effect imports.
["^\\u0000"],
// Parent imports. Put `..` last.
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
// Other relative imports. Put same-folder imports and `.` last.
["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
// Style imports.
["^.+\\.?(css)$"]
]
}
],
"simple-import-sort/exports": "error"
}
}
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "simple-import-sort"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"rules": {
"@typescript-eslint/consistent-type-imports": "error",
"simple-import-sort/imports": [
"error",
{
"groups": [
// Packages `react` related packages come first.
["^react", "^@?\\w"],
// Internal packages.
["^(@|components)(/.*|$)"],
// Side effect imports.
["^\\u0000"],
// Parent imports. Put `..` last.
["^\\.\\.(?!/?$)", "^\\.\\./?$"],
// Other relative imports. Put same-folder imports and `.` last.
["^\\./(?=.*/)(?!/?$)", "^\\.(?!/?$)", "^\\./?$"],
// Style imports.
["^.+\\.?(css)$"]
]
}
],
"simple-import-sort/exports": "error"
}
}
Yet the sort isnt working. Anyone ?
1 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/6/2022 in #questions
TypeError resolver is not a function at apiauthsession endpoint
Im trying to configure Google Credentials with the Google API to have the login working. Ive put the URI redirect to http://localhost:3001/api/auth/callback/google (im using port 3001) On my Signup button i have
import { signIn } from "next-auth/react";

<button
onClick={() =>
signIn("google", {
callbackUrl: "http://localhost:3002",
})
}
import { signIn } from "next-auth/react";

<button
onClick={() =>
signIn("google", {
callbackUrl: "http://localhost:3002",
})
}
on the nextAuth file:
export const authOptions: NextAuthOptions = {
providers: [
DiscordProvider({
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
}),
GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
}),
]
};
export const authOptions: NextAuthOptions = {
providers: [
DiscordProvider({
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
}),
GoogleProvider({
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
}),
]
};
Clicking the button tho will give me a
​ GET http://localhost:3001/api/auth/error 500 (Internal Server Error)
Server Error
TypeError: resolver is not a function

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.apiResolver
file:///Users/fernandocorreia/Documents/fitnessapp/fitness-app/node_modules/next/dist/server/api-utils/node.js (367:15)
​ GET http://localhost:3001/api/auth/error 500 (Internal Server Error)
Server Error
TypeError: resolver is not a function

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.apiResolver
file:///Users/fernandocorreia/Documents/fitnessapp/fitness-app/node_modules/next/dist/server/api-utils/node.js (367:15)
Kinda learning how this stack works and a bit blind on this one, if anyone has any tip would be greatly appreciated. https://github.com/FACorreiaa/FitME If anyone has 5mins to spare, im sure more experienced people with this stack could see what im doing wrong. tyvm
7 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/2/2022 in #questions
Type 'ZodObject{ id ZodNumber; first_name ... missing but required in _procedure
So im trying to pass the logic I had on my Nest + Prisma + GraphQL to the ct3 stack and im a beginner with trpc which makes it even more exciting! The objective of my web application is to have a system where users can manage their workout and meal plans and, in case they dont have no idea of what they are doing, give them plan suggestions based on their weight, daily activity, etc. I installed the package zod-prisma so i dont have to write everything by hand. So based on my Prisma model i have
export const UserModel = z.object({
id: z.number().int(),
first_name: z.string().nullish(),
last_name: z.string().nullish(),
gender: z.string(),
email: z.string(),
nickname: z.string(),
password: z.string(),
emailVerified: z.date().nullish(),
createdAt: z.date(),
updatedAt: z.date(),
})
export const UserModel = z.object({
id: z.number().int(),
first_name: z.string().nullish(),
last_name: z.string().nullish(),
gender: z.string(),
email: z.string(),
nickname: z.string(),
password: z.string(),
emailVerified: z.date().nullish(),
createdAt: z.date(),
updatedAt: z.date(),
})
And on my user-login router I tought i could do something like:
import { z } from "zod";
import { UserModel } from '../../../../prisma/zod/user'
import { router, publicProcedure } from "../trpc";

export const userLoginRouter = router({
input: UserModel,
getUsers: publicProcedure.query(({ ctx }) => {
return ctx.prisma.user.findMany({})
}),
getUser: publicProcedure.query(({ ctx }) => {
const { id } = input;
return ctx.prisma.user.findUnique({
where: {
id
}
})
}),
});
import { z } from "zod";
import { UserModel } from '../../../../prisma/zod/user'
import { router, publicProcedure } from "../trpc";

export const userLoginRouter = router({
input: UserModel,
getUsers: publicProcedure.query(({ ctx }) => {
return ctx.prisma.user.findMany({})
}),
getUser: publicProcedure.query(({ ctx }) => {
const { id } = input;
return ctx.prisma.user.findUnique({
where: {
id
}
})
}),
});
Which i see now its not the right way to do. I probably have to read the documentation a bit better but i accept any tips to lead me on the right direction.
4 replies
TTCTheo's Typesafe Cult
Created by Knox on 12/1/2022 in #questions
Adapt create t3 for mobile backend app?
Im building a fitness application right now with nest, prisma and graphql for my backend. Ive gotten highly interested in changing my code for this specific one. Im just wondering, i also want to adapt my endpoints to a mobile app in the future, ill think if i go native code or not. From what i see in the code, this is not possible to do with create t3, right ? Since there aren't declared endpoins ? I saw tcrp can be extended to have declarative rest endpoints, but would this still be a good solution if one was thinking about building a mobile version of the web app in the future? Would a mobile app be able to consume the server part of this mono repo ?
11 replies
TTCTheo's Typesafe Cult
Created by Knox on 11/18/2022 in #questions
Graphql schema first or code first ?
Im currently building an app, for something i will use but as an hobby, using NestJS, GraphQL and Prisma. I have read about both approaches, and i find the schema first very interesting because it allows everyone to understand the API whatever language is used on the backend. Since im using Typescript and I will be working, I was wondering if the code first approach wouldn't make me write less code specially because Nest has a plugin that allows to not use decorators on every property, which makes the code cleaner. But I dont have enough Graphql experience to understand if with the schema first when i scale the app, if i will write alot more code or not. But i accept all the feedback.
28 replies