Richard Scarrott
10/03/2022, 8:58 AMprisma.user.findUnique('usr_123'); // DB query
// Somewhere else (potentially in a different tick)
prisma.user.findUnique('usr_123'); // Another DB query :(
Łukasz Usarz
10/03/2022, 9:44 AMLloyd Richards
10/03/2022, 2:55 PMschema.prisma
and DATABASE_URL
and setting up a second @internal/prisma/client
on my graphQL context. The issue came when i tried to deploy this to Cloud Functions as each time i would get an error saying that @internal/prisma/client
was not found in the node_module. i tried several possible solutions like creating an alias for the legacy prisma client or for both but it never worked.
The _temp Solution: In the end i figured i could just build the second prisma client outside of the node_module and commit it with the rest of my code. The result was something like this:
Structure
.
├── functions
│ ├── @internal # This is the Legacy @PrismaClient
│ ├── node_module # (.gitignore) In here is the default @PrismaClient
│ ├── prisma
│ │ └── schema.prisma # The Prime Schema for CloudSQL
│ ├── prisma_legacy
│ │ └── schema.prisma # The Legacy Schema for MySQL Server
│ ├── src # Rest of the functions and graphql code first
│ ├── package.json
│ └── ...
└── ...
Legacy schema.prisma
generator client {
provider = "prisma-client-js"
output = "../@internal/prisma/client"
binaryTargets = ["debian-openssl-1.1.x"]
}
datasource db {
provider = "mysql"
url = env("LEGACY_DATABASE_URL")
}
... # Rest of the schema
If someone knows how to correctly alias the prisma client do i can have something like:
"dependencies": {
"@prime/prisma/client" : "npm:@prisma/client@4.4.0",
"@legacy/prisma/client" : "npm:@prisma/client@4.4.0",
...
}
Lars Ivar Igesund
10/03/2022, 7:42 PMSebastian Gug
10/03/2022, 8:57 PMSebastian Gug
10/03/2022, 8:58 PMexport class UserModel implements Prisma.UserCreateInput {
this worksven v
10/03/2022, 9:08 PMTomasz Koszykowski
10/03/2022, 10:36 PMshawng
10/03/2022, 10:44 PMcheckIfUserIsActive(prisma_user){
return prisma_user.is_active;
}
Thanks in advance!Brothak
10/04/2022, 4:56 AMPerez cato Cato perez
10/04/2022, 5:46 AMFrancis Shonubi
10/04/2022, 8:16 AMprisma db push
should be used for prototyping so you can easily change things on the go. I ran that and the local prisma client got updated but I am having TypeError: Cannot read properties of undefined
in my docker container, I am not having an errors in my code editor and I am getting auto completion. I tried building the container again, still the same error.
I tried rm -rf node_modules && npm i && docker container prune
then docker compose up --build
, still the same TypeError.
I not very good at docker so I can't really tell what the problem is.Ben Liger
10/04/2022, 9:20 AMUser
s that have not yet been added to the friendList
of a particular user?
model User {
friendList User[]
}
// I would like to get a list of users where user A has not yet connected them to their friendList
Barnaby
10/04/2022, 10:49 AMSebastian Gug
10/04/2022, 11:24 AMmodel Session {
id String @id @default(uuid())
user User @relation(fields: [userId], references: [id])
userId String
But then the create input expects to have a User provided? Isn't that data that will be joined on the user? what's the correct way of defining this?
The type error in question:
Class 'SessionModel' incorrectly implements interface 'SessionCreateInput'.
Property 'user' is missing in type 'SessionModel' but required in type 'SessionCreateInput'.
Joey
10/04/2022, 4:26 PMselect: {
members: true,
organizationInvites: 0,
organizationRequests:0
},
any way to achieve that without just setting the values manually after the query?Boo
10/04/2022, 5:42 PMNOT: {
posts: {
some: {
postId: {
gte: 0,
},
},
},
},
David Hancu
10/04/2022, 6:16 PMJoey
10/04/2022, 6:43 PMconst updateModel = (id: string, data: Partial<Model>) =>db.model.update({ where: { id }, data });
When hovering the data object it says the type is Partial<Model>
but this throws a type error when trying to include a connect/disconnect on the relationshipSebastian Gug
10/04/2022, 6:43 PMUserCreateNestedOneWithoutSessionsInput'
-- that prisma sets for the resulting session model in this scenario:
model Session {
id String @id @default(uuid())
user User @relation(fields: [userId], references: [id])
userId String
createdAt DateTime? @default(now())
updatedAt DateTime? @default(now())
}
Sebastian Gug
10/04/2022, 7:35 PMKevin Lanthier
10/04/2022, 8:11 PMAndrás Bácsai
10/04/2022, 9:03 PMJonathan Marbutt
10/05/2022, 3:04 AMYunbo
10/05/2022, 4:35 AMconnect
when do i use it?
let's say i have a model
Profile
{
id number;
name string;
posts Post[];
}
Post
{
id number;
message string;
profileId number;
profile Profile @relation(fields: [profileId], references: [id])
}
and in code,
prisma.post.create({
data: {
message: 'hello',
profileId: 1,
}
})
it's not exact example but when i'm coding, sometimes it works, sometimes i had to use connect
(in other scenarios)
prisma.post.create({
data: {
message: 'hello',
profile: {
connect: {
id: 1,
}
}
}
})
i can not seem to find a documentation or resource about connect
could anyone tell me when to use connect
?Jarupong
10/05/2022, 6:44 AMMarten Tamm
10/05/2022, 8:33 AMDavid Hancu
10/05/2022, 9:18 AMJose Rangel
10/05/2022, 9:40 AM// API handler
import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient, Product } from '../../../../prisma/.generated/client';
const prismaClient = new PrismaClient();
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const {lang, country, slug} = req.query;
try {
const product: Product = await prismaClient.product.findFirst({
where: {
slug: slug,
locale: lang,
country: country,
},
});
if (product) {
res.status(200).json({ product });
} else {
res.status(404).json({
status: 404,
err: `Product not found`,
});
}
} catch (err) {
res.status(500).json({ err: err });
} finally {
await prismaClient.$disconnect();
}
};
export default handler;
// client.ts
import { PrismaClient } from '@src/prisma/.generated/client'; // importing from the generated Prisma Client to have Intellisense functionality
const prisma = new PrismaClient();
export default prisma;
// singleton.ts
import { PrismaClient } from '@src/prisma/.generated/client';
import { DeepMockProxy, mockDeep, mockReset } from 'jest-mock-extended';
import prisma from './client';
jest.mock('./client', () => ({
__esModule: true,
default: mockDeep<PrismaClient>(),
}));
beforeEach(() => {
mockReset(prismaMock);
});
export const prismaMock = prisma as unknown as DeepMockProxy<PrismaClient>;
// unit.spec.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { Product } from '@src/prisma/.generated/client';
import { createMocks, RequestMethod } from 'node-mocks-http';
import handler from '../../../pages/api/[language-country]/p/[slug]';
import { prismaMock } from './__mocks__/singleton';
describe('/api/[language-country]/p/[slug] API Endpoint', () => {
const lang = 'xx';
const country = 'xx';
const slug = 'slug';
function mockRequestResponse(method: RequestMethod) {
const { req, res }: { req: NextApiRequest; res: NextApiResponse } = createMocks({ method });
req.query = { 'lang': `${lang}`, 'country': `${country}`, slug: `${slug}` };
return { req, res };
}
it('should return 200 if product found by lang, country, slug', async () => {
const mockData: Product = {
// Product fields with mock data
}
const { req, res } = mockRequestResponse('GET');
// Mocking findFirst, which is used in the handler() function
prismaMock.product.findFirst.mockResolvedValue(mockData);
// Run handler() function that calls the Prisma function findFirst()
await handler(req, res);
// Expectation would be that the statusCode is 200 because I'm saying in the code that the return of mocked findFirst() is the mocked Product
// It returns 404 because with the params given in req, there are no products in the actual database
expect(res.statusCode).toBe(200);
});
});
Lucian Buzzo
10/05/2022, 10:34 AMprisma.$connect()
on every request, which is not ideal.