EQ
EQ
Explore posts from servers
TTCTheo's Typesafe Cult
Created by EQ on 2/25/2024 in #questions
Image uploading concurrency Prisma
Hello, I am using Cloudflare as CDN and the upload size limit is 100MB. I want to upload multiple images that may be in total bigger than 100MB. I thought of splitting the images to its own requests so 10 images are 10 requests to upload to compatible S3 storage (Backblaze B2). I have an Image model and each user can have a max of 15 images saved in the database. Currently I do transaction like this:
let retries = 0;
while (retries <= MAX_UPLOAD_PROJECT_IMAGE_RETRIES) {
try {
return this.prisma.$transaction(
async (tx) => {
const project = await tx.project.findUnique({...});
// If the project has already reached the max amount of images.
if (project.images.length >= MAX_PROJECT_IMAGES)
throw new ConflictException('MAX_IMAGES_REACHED');

// Save the image path in database.
const uploadedImage = await tx.image.create({
data: {
path: fileKey,
project: {
connect: {
id: projectId
}
}
},
select: {
id: true,
path: true
}
});
// Upload the file to S3.
await this.storageService.uploadFile(
fileKey,
fileBuffer
);
},
{
isolationLevel: 'Serializable',
timeout: 15000
}
)
} catch (e) {
if (e.code === 'P2034' && retries < MAX_UPLOAD_PROJECT_IMAGE_RETRIES) {
retries++;
} else {
await this.storageService.deleteFile(fileKey);
throw e;
}
}
}
let retries = 0;
while (retries <= MAX_UPLOAD_PROJECT_IMAGE_RETRIES) {
try {
return this.prisma.$transaction(
async (tx) => {
const project = await tx.project.findUnique({...});
// If the project has already reached the max amount of images.
if (project.images.length >= MAX_PROJECT_IMAGES)
throw new ConflictException('MAX_IMAGES_REACHED');

// Save the image path in database.
const uploadedImage = await tx.image.create({
data: {
path: fileKey,
project: {
connect: {
id: projectId
}
}
},
select: {
id: true,
path: true
}
});
// Upload the file to S3.
await this.storageService.uploadFile(
fileKey,
fileBuffer
);
},
{
isolationLevel: 'Serializable',
timeout: 15000
}
)
} catch (e) {
if (e.code === 'P2034' && retries < MAX_UPLOAD_PROJECT_IMAGE_RETRIES) {
retries++;
} else {
await this.storageService.deleteFile(fileKey);
throw e;
}
}
}
But I don't like this way since everyone who tries to upload is waiting because of 1 image. I woud like to lock per user rather than lock whole table.
3 replies
TTCTheo's Typesafe Cult
Created by EQ on 7/24/2023 in #questions
Prisma Return Type
Hello, I have the following:
async findOne<T extends Prisma.UserSelect>(
email: string,
select: T
): Promise<Prisma.UserGetPayload<{ select: T }>> {
const user = await this.prisma.user.findUnique({
where: { email: email },
select: { ...select }
});
return user;
}
async findOne<T extends Prisma.UserSelect>(
email: string,
select: T
): Promise<Prisma.UserGetPayload<{ select: T }>> {
const user = await this.prisma.user.findUnique({
where: { email: email },
select: { ...select }
});
return user;
}
But I get an error on the "return".
Type '(T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exte...' is not assignable to type 'T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exten...'.
Type 'null' is not assignable to type 'T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exten...'.

52 return user;
Type '(T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exte...' is not assignable to type 'T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exten...'.
Type 'null' is not assignable to type 'T extends undefined ? GetResult<{ id: string; created_at: Date; updated_at: Date; email: string; password: string; first_name: string; last_name: string; role: Role; }, unknown, never> & {} : { [K in keyof T as T[K] extends false | ... 1 more ... | undefined ? never : K]: T[K] extends object ? UserPayload<...> exten...'.

52 return user;
Does someone know how to fix it?
7 replies
TTCTheo's Typesafe Cult
Created by EQ on 6/11/2023 in #questions
One to one and one to many
Hello, I currently have
model Event {
active_meeting_id String?
active_meeting Meeting @relation(name: "active_meeting", fields: [active_meeting_id], references: [id])

old_meetings Meeting[] @relation(name: "old_meetings")
}

model Meeting {
event_id String?
event Event? @relation(name: "active_meeting")
old_event Event? @relation(name: "old_meetings", fields: [event_id], references: [id])
}
model Event {
active_meeting_id String?
active_meeting Meeting @relation(name: "active_meeting", fields: [active_meeting_id], references: [id])

old_meetings Meeting[] @relation(name: "old_meetings")
}

model Meeting {
event_id String?
event Event? @relation(name: "active_meeting")
old_event Event? @relation(name: "old_meetings", fields: [event_id], references: [id])
}
But when I for example create an active meeting, the event_id stays null. Of course, I don't assign it to the active_meeting but idk how to do. Before this, I just had an event field with Event? type and events with Event[] but a meeting can only have 1 event, not an array and both event and old_event refer to the same event. Does someone know how to do this properly?
3 replies
TTCTheo's Typesafe Cult
Created by EQ on 6/10/2023 in #questions
Prisma Date Day Off
Hello, I currently have the following:
model SomeModel {
date DateTime @db.Date()
}
model SomeModel {
date DateTime @db.Date()
}
prisma.somemodel.insert({
data: {
date: new Date("2023-06-10")
}
});
prisma.somemodel.insert({
data: {
date: new Date("2023-06-10")
}
});
but the problem is that it saves the date as 2023-06-09 in the PostgreSQL database. Idk how to fix this
9 replies
TTCTheo's Typesafe Cult
Created by EQ on 3/28/2023 in #questions
Difference between where in Prisma
Hello, is there a difference between this beside how you write it?
await prisma.user.count({
where: {
post: { // between this
id: postId
}
post_id: postId // and this
}
})
await prisma.user.count({
where: {
post: { // between this
id: postId
}
post_id: postId // and this
}
})
4 replies
TTCTheo's Typesafe Cult
Created by EQ on 2/25/2023 in #questions
Prisma model name preferences
Hello, What do you guys prefer or what is the "right" thing to do?
model User {
...
date_created
or
dateCreated @@map("date_created")
@@map("user")
}
model User {
...
date_created
or
dateCreated @@map("date_created")
@@map("user")
}
2 replies
TTCTheo's Typesafe Cult
Created by EQ on 2/18/2023 in #questions
Prisma multi schema CLI
Hello, Is it possible to only force reset one schema when using multiple schemas? For example, to push to db and reset everything in the database, you use something like npx prisma db push --force-reset But how can I for example only do this for the schema places?
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 1/9/2023 in #questions
React Select - Unselect and remove placeholder when clearing input
Hello, When I select something and then delete the input, it still shows the chosen option in the placeholder and does not remove the chosen option. I want to unchoose the chosen option when the input changes and not show the chosen option in the placeholder when input is empty. Anyone have an idea on how to fix this? Currently, it is like in the video
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 1/1/2023 in #questions
NextJS middleware
Hello, In the middleware file, I want to check if the user is authenticated and allowed to visit specific pages. Currently how I do it is as following:
// Some page
const Page = () => { ... }

Page.auth = {
route: "/page"
protectFromNonAuth: {
roles: ["ADMIN"]
}
}

// NextJS Middleware file
const routes = [
{
route: "/page"
protectFromNonAuth: {
roles: ["ADMIN"]
}
}
]

export const middleware = async (req: NextRequest) => {
// Get the current route and find it in the routes array and check if user has
// permission to visit the page.
}
// Some page
const Page = () => { ... }

Page.auth = {
route: "/page"
protectFromNonAuth: {
roles: ["ADMIN"]
}
}

// NextJS Middleware file
const routes = [
{
route: "/page"
protectFromNonAuth: {
roles: ["ADMIN"]
}
}
]

export const middleware = async (req: NextRequest) => {
// Get the current route and find it in the routes array and check if user has
// permission to visit the page.
}
This works but what I don't like about it is that I now have double code for the same thing. When I import the auth functionality from all the pages, so like
const routes = [
Page.auth,
OtherPage.auth
];
const routes = [
Page.auth,
OtherPage.auth
];
it works in dev mode but when building for production, it says Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime because I import those auth from the pages. Does someone know a better and cleaner way of doing this? I have quite some pages and I don't want to forgot also adding the auth in the routes array in the middleware.
4 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/25/2022 in #questions
Prisma Disconnect Where
Hello, Does someone know how I can disconnect a relation between 2 models based on the id's in an array? I.e.
await prisma.project.update({
where: {
id: projectId
},
data: {
users: {
disconnect: {
id: {
// Disconnect all users that do not have the ID of one of those
not: ["user_id_1", "user_id_45", "user_id_938"]
}
}
}
}
})
await prisma.project.update({
where: {
id: projectId
},
data: {
users: {
disconnect: {
id: {
// Disconnect all users that do not have the ID of one of those
not: ["user_id_1", "user_id_45", "user_id_938"]
}
}
}
}
})
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/23/2022 in #questions
AWS Spending Limit
Hello, Recently, I have heard that you can now set a hard spending limit on AWS services and if you have reached the limit, the service stops. I want to use this for AWS SES for sending e-mails but don't know if you really can set spending limits.
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/17/2022 in #questions
Zod - `require_error` in string not working when also using `min`
Does someone know how I can show the required_error in Zod?
z.string({ require_error: "Name is required"}).min(2, { message: "Name must be at least 2 characters"});
z.string({ require_error: "Name is required"}).min(2, { message: "Name must be at least 2 characters"});
when I parse this, it only shows that I need at least 2 characters, even if the string is empty
5 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/12/2022 in #questions
Presigned URL Error Handling
I have a question about uploading images to an S3 compatible storage service. 1. Let's say in the site a user uploads multiple images. 2. A request is sent to the backend (without the images). 3. The backend generates names for the images and stores them in a database with the generated names. 4. Create a presigned url for each image. 5. The request sends the presigned urls back to the user on the site. 6. There are a total of 5 images, 2 have successfully uploaded via the presigned url, the rest have failed for 1 reason or another. 7. What do I have to do now? Do I have to send presigned urls again to delete the files and to delete the data in the database or do I have to do something else? Or what should I do if the presigned url expires because the user has a slow internet connection?
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/3/2022 in #questions
Is it safe to save user role in JWT token with NextAuth?
Hello, When using the JWT strategy, NextAuth puts the user role automatically in the token. Is this safe to do? If I google it, its a bit of a yes-no answer. If I look at Cal.com, they even put more information in it. I want to use the role only to check if authenticated user is allowed to visit a specific page. Of course, everytime a user does an action, it will be checked if the user is allowed via a middleware.
47 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/3/2022 in #questions
Next Auth JWT
Hello, I have 3 questions regarding NextAuth with JWT as session strategy: 1. When I return in the authorize function something like
return {
email: user.email
};
return {
email: user.email
};
I get an error that authorize does not match the User type of NextAuth. I have tried to override this in next-auth.d.ts file, unfortunately it did not work. 2. It it save to also send the user role in authorize? 3. Does the JWT refresh automatically when it expires when using CredentialsProvider?
4 replies
TTCTheo's Typesafe Cult
Created by EQ on 12/2/2022 in #questions
Stack choice
Hello, I am currently using Next.js, React, Typescript and Axios for my frontend stack and Nest.js, Typescript, Swagger (OpenAPI) and Prisma for backend stack. This way, I can generate the types based on the manual made classes (DTO etc.) that Swagger recognises. However, it is a bit of a mess to generate the types. I am building a platform where people can find businesses to let them do home services. I was wondering if tRPC would be useful in this case? Let's say that in the future, I wanted to publish an API where businesses could fetch stuff, would it be easy to do this with tRPC? Are there also other things to consider when removing an external backend and use the backend of Next.js? Also for hosting, must I use Vercel or can I also freely choose one my own? Will using the backend of Next.js have performance drawbacks compared to an external one?
1 replies
TTCTheo's Typesafe Cult
Created by EQ on 10/8/2022 in #questions
Analytics Platform
Hello, what analytics platform do you guys recommend to use? I thought of maybe using Google Analytics but saw in the past that countries were trying to ban them.
5 replies