sommeeeR
sommeeeR
Explore posts from servers
PPrisma
Created by sommeeeR on 10/19/2024 in #help-and-questions
Lambda Layer
No description
4 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 6/17/2024 in #questions
Storing ab access token in memory server-side in NextJS
How can i store a token in-memory server-side in a Next.JS project? I tried doing this:
export let accessToken: AccessToken | undefined;

export async function getAccessToken(): Promise<string | undefined> {
console.log(accessToken);
if (accessToken && +accessToken.expires_on > Date.now() / 1000) {
return accessToken.access_token;
} else {
try {
const token = await client.auth.getToken(clientId, clientSecret);
if (token.ok) {
accessToken = token.data;
return token.data.access_token;
}
} catch (err) {
}
return undefined;
}
}
export let accessToken: AccessToken | undefined;

export async function getAccessToken(): Promise<string | undefined> {
console.log(accessToken);
if (accessToken && +accessToken.expires_on > Date.now() / 1000) {
return accessToken.access_token;
} else {
try {
const token = await client.auth.getToken(clientId, clientSecret);
if (token.ok) {
accessToken = token.data;
return token.data.access_token;
}
} catch (err) {
}
return undefined;
}
}
then i have a function that gets it, or refreshes it depending on expiration time... the problem however is that it goes back to undefined, after being set for some reason. lets say i have this API route handler to test getting a token: /api/test/:
import { getAccessToken } from '@/lib/vipps';

export const dynamic = 'force-dynamic';

export async function GET() {
const token = await getAccessToken();

return Response.json({
retrivedToken: token,
});
}
import { getAccessToken } from '@/lib/vipps';

export const dynamic = 'force-dynamic';

export async function GET() {
const token = await getAccessToken();

return Response.json({
retrivedToken: token,
});
}
if i curl http://localhost:3000/api/test i will get the same token back and i will get the stored one until go to different routes, and then come back to curling the test it is undefined. what am i missing here? maybe it gets redeclared somehow?
2 replies
PPrisma
Created by sommeeeR on 4/26/2024 in #help-and-questions
anyway i can have the _sum in this findMany()
Anyway I can have the _sum in findMany() or should i use typescript to get the sum?
const bookings = await db.booking.findMany({
select: {
courseId: true,
totalPersons: true
},
});

const sum = await db.booking.aggregate({
_sum: {
totalPersons: true,
},
});
const bookings = await db.booking.findMany({
select: {
courseId: true,
totalPersons: true
},
});

const sum = await db.booking.aggregate({
_sum: {
totalPersons: true,
},
});
2 replies
PPrisma
Created by sommeeeR on 4/12/2024 in #help-and-questions
Returning the next day closest to NOW
So I have a list of dates, and im trying to return the next date that is closest to new Date.now(); Here is the code:
const course = await db.course.findFirst({
where: {
id: params.id,
},
include: {
courseDate: {
where: {
from: {
gte: new Date(),
},
},
take: 1,
},
},
});
const course = await db.course.findFirst({
where: {
id: params.id,
},
include: {
courseDate: {
where: {
from: {
gte: new Date(),
},
},
take: 1,
},
},
});
This doesnt work it returns :
[
{
id: 10,
from: 2024-04-13T10:00:00.000Z,
to: 2024-04-13T14:00:00.000Z,
courseId: 8
}
]
[
{
id: 10,
from: 2024-04-13T10:00:00.000Z,
to: 2024-04-13T14:00:00.000Z,
courseId: 8
}
]
This is my entire courseDate array: https://bpa.st/NK6Q - as you can see there the closest date from now(2024-04-12T06:04:45.733Z) should be the courseDate with id: 21. Anyone know what it might be ? 🙂
2 replies
PPrisma
Created by sommeeeR on 4/11/2024 in #help-and-questions
Get the next date with prisma
const course = await db.course.findFirst({
where: {
slug: params.slug,
},
include: {
courseDate: { // i want the next one from NOW
orderBy: {
from: 'asc',
}
},
},
});
const course = await db.course.findFirst({
where: {
slug: params.slug,
},
include: {
courseDate: { // i want the next one from NOW
orderBy: {
from: 'asc',
}
},
},
});
guys i want to get next courseDate from today and only that one. how can i do that using this query? 🙂
10 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 11/30/2023 in #questions
Revalidating a SSG path in a tRPC procedure
Hello guys, how could I revalidate a path in a tRPC procedure? I have a NextJS pages site that is mainly SSG with an admin panel. When a user creates a new blogpost for.example I want to revalidate that path (ISR) (https://nextjs.org/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#using-on-demand-revalidation). How could I do that? I probably need the Response object from NextJS This is my procedure:
createBlogPost: protectedProcedure
.input(blogPostSchema)
.mutation(async ({ input }) => {
const blogpost = await db.blogPost.create({
data: {
title: input.title,
body: input.body,
post_date: input.post_date,
image_url: input.image_url,
},
});
return blogpost;
}),
}),
createBlogPost: protectedProcedure
.input(blogPostSchema)
.mutation(async ({ input }) => {
const blogpost = await db.blogPost.create({
data: {
title: input.title,
body: input.body,
post_date: input.post_date,
image_url: input.image_url,
},
});
return blogpost;
}),
}),
8 replies
TtRPC
Created by sommeeeR on 11/28/2023 in #❓-help
I want to refetch and set the inital data of an useState
Hello guys, currently i am retrieving the data i use in useState with SSR, but i want to use somethinng that makes it possible to update the useState on interactions from the user. Im guessing I should use useQuery?
How can i set it so initialData in my useState works. this is my current useState line:
const [items, setItems] = useState(cat.CatImage);
const [items, setItems] = useState(cat.CatImage);
6 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 11/21/2023 in #questions
Error: ❌Attempted to access a server-side environment variable on the client - Weird T3 Stack bug
No description
26 replies
TtRPC
Created by sommeeeR on 11/3/2023 in #❓-help
Check if Role is ADMIN
Hey guys I have a private procedure in T3 Stack. I need to check if the user thats doing the action is indeed admin. How can i implement that in this privateProcedure?
import { z } from "zod";

import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { db } from "~/server/db";

export const userRouter = createTRPCRouter({
delete: protectedProcedure.input(z.string()).mutation(async ({ input }) => {
const msg = await db.user.findFirst({ where: { id: input } });
if (!msg) {
return { success: false, msg: "User not found" };
}
await db.user.delete({ where: { id: input } });
return { success: true, msg };
}),
});
import { z } from "zod";

import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { db } from "~/server/db";

export const userRouter = createTRPCRouter({
delete: protectedProcedure.input(z.string()).mutation(async ({ input }) => {
const msg = await db.user.findFirst({ where: { id: input } });
if (!msg) {
return { success: false, msg: "User not found" };
}
await db.user.delete({ where: { id: input } });
return { success: true, msg };
}),
});
3 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 11/3/2023 in #questions
why is session undefined even tho i know it exists
I cant access the Session in my Admin component. its undefined. whats wrong?
import { Role } from "@prisma/client";
import Layout from "./Layout";
import type { GetServerSideProps } from "next/types";
import { getServerAuthSession } from "~/server/auth";
import type { Session } from "next-auth";

export default function Admin({ session }: { session: Session }) {
console.log(session);
if (!session || session.user.role !== Role.ADMIN) {
return <div>Unauthorized.</div>;
}
return <Layout>hi</Layout>;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
const session = await getServerAuthSession(ctx);
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}

return {
props: {
session,
},
};
};
import { Role } from "@prisma/client";
import Layout from "./Layout";
import type { GetServerSideProps } from "next/types";
import { getServerAuthSession } from "~/server/auth";
import type { Session } from "next-auth";

export default function Admin({ session }: { session: Session }) {
console.log(session);
if (!session || session.user.role !== Role.ADMIN) {
return <div>Unauthorized.</div>;
}
return <Layout>hi</Layout>;
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
const session = await getServerAuthSession(ctx);
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}

return {
props: {
session,
},
};
};
2 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 10/30/2023 in #questions
Creating an admin dashboard, and im worried about my users on my main site
I have a site that is mainly SSG and CSR. now i want to create an /admin/ route where theres gonna be an admin dashboard to work with the database. Would my users need to load a lot of bundle from what i create in the /admin route or dont I have to care about that? The admin route gonna be a lot of SSG and probably some UI library that the users of the site is not using. I dont want my users to load unnecessary stuff. Whats the approach I need to use ? Btw, my site is created with the Pages router
4 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 10/19/2023 in #questions
Get IP Address in tRPC router
Hey guys how can I get the IP address inside a procedure? Like this code f.ex:
export const contactRouter = createTRPCRouter({
hello: publicProcedure
.input(contactSchema)
.mutation(async ({ input, ctx }) => {
// get ip here
const msg = await db.contactMessage.create({
data: {
name: input.name,
email: input.email,
subject: input.subject,
message: input.message,
},
});
return { success: true, msg };
}),
});
export const contactRouter = createTRPCRouter({
hello: publicProcedure
.input(contactSchema)
.mutation(async ({ input, ctx }) => {
// get ip here
const msg = await db.contactMessage.create({
data: {
name: input.name,
email: input.email,
subject: input.subject,
message: input.message,
},
});
return { success: true, msg };
}),
});
15 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 9/22/2023 in #questions
Add a property on my cat.CatImage object
Hello guys! I got this [slug].tsx page using the pages router in NextJS with T3Stack. How could I add .blur property on the object cat.CatImage Now im archieving it with passing the CatImages with blur property as a seperate prop. I want to archieve it using the original cat object. Here is the code: getBase64.ts: https://bpa.st/QJ7A [slug].tsx: https://bpa.st/JFXQ
4 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 9/21/2023 in #questions
T3-stack SSG
Hey guys, im creating a site with the pages router. Im wondering if its possible to create most of it with SSG? Since most of the pages only needs to be populated with data at build time. What do I do ? I use getStaticProps()and getStaticPaths() etc? And it will automatically SSG them at build time?
6 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 9/8/2023 in #questions
How can I useQuery when I click a button
I have this privateProcedure on the backend. I want to call it when I hit a button in my frontend:
checkDate: protectedProcedure
.input(z.object({ date: z.date() }))
.query(({ input, ctx }) => {
return {
message: 'hello world ' + input.date.toISOString(),
};
}),
checkDate: protectedProcedure
.input(z.object({ date: z.date() }))
.query(({ input, ctx }) => {
return {
message: 'hello world ' + input.date.toISOString(),
};
}),
How do I do that? I am btw gonna query a database for that date, and return something. I just simplified it for this example
10 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 9/6/2023 in #questions
tRPC useQuery() or useMutation()
I have a component with a form containing a question about a secret name. When submitting that form I want to validate that the user sent the correct secret name. What should I use? (the name will be in my environment variables) Im currently trying to implement it with useMutation(). Is this the correct method to use? This is what I have so far:
const { mutate } = api.userRouter.checkCatName.useMutation();
const handleSubmit = (values: { catName: string }) => {
const res = mutate(values);
console.log(res);
};
const { mutate } = api.userRouter.checkCatName.useMutation();
const handleSubmit = (values: { catName: string }) => {
const res = mutate(values);
console.log(res);
};
its currently working, but i cant f.ex do console.log(res.result) I then get an error Cannot read properties of undefined. This is the procedure code:
checkCatName: protectedProcedure
.input(z.object({ catName: z.string().min(1).max(20) }))
.mutation(({ input }) => {
if (input.catName === 'secret') {
return 'you did it!';
}
return 'you are bad';
}),
checkCatName: protectedProcedure
.input(z.object({ catName: z.string().min(1).max(20) }))
.mutation(({ input }) => {
if (input.catName === 'secret') {
return 'you did it!';
}
return 'you are bad';
}),
8 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 8/20/2023 in #questions
Next-Auth
If you use T3 stack with the default auth settings and Oauth providers. does it auto refresh ? Or do you have to implement things for it?
8 replies
TTCTheo's Typesafe Cult
Created by sommeeeR on 8/20/2023 in #questions
Adding roles to Next Auth when using Discord or Facebook providee
How can I add a role to a user. I have 2 admins and the rest are normal users.
8 replies