GithubHelp home page GithubHelp logo

blogr-nextjs-prisma's Introduction

Prisma

Prisma

Discord

Quickstart   •   Website   •   Docs   •   Examples   •   Blog   •   Discord   •   Twitter

What is Prisma?

Prisma is a next-generation ORM that consists of these tools:

  • Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
  • Prisma Migrate: Declarative data modeling & migration system
  • Prisma Studio: GUI to view and edit data in your database

Prisma Client can be used in any Node.js or TypeScript backend application (including serverless applications and microservices). This can be a REST API, a GraphQL API, a gRPC API, or anything else that needs a database.

The Prisma ORM can also further be extended with these Prisma products:

Getting started

The fastest way to get started with Prisma is by following the Quickstart (5 min).

The Quickstart is based on a preconfigured SQLite database. You can also get started with your own database (PostgreSQL and MySQL) by following one of these guides:

How Prisma works

This section provides a high-level overview of how Prisma works and its most important technical components. For a more thorough introduction, visit the Prisma documentation.

The Prisma schema

Every project that uses a tool from the Prisma toolkit starts with a Prisma schema file. The Prisma schema allows developers to define their application models in an intuitive data modeling language. It also contains the connection to a database and defines a generator:

// Data source
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

// Generator
generator client {
  provider = "prisma-client-js"
}

// Data model
model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields:  [authorId], references: [id])
  authorId  Int?
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

In this schema, you configure three things:

  • Data source: Specifies your database connection (via an environment variable)
  • Generator: Indicates that you want to generate Prisma Client
  • Data model: Defines your application models

The Prisma data model

On this page, the focus is on the data model. You can learn more about Data sources and Generators on the respective docs pages.

Functions of Prisma models

The data model is a collection of models. A model has two major functions:

  • Represent a table in the underlying database
  • Provide the foundation for the queries in the Prisma Client API

Getting a data model

There are two major workflows for "getting" a data model into your Prisma schema:

  • Generate the data model from introspecting a database
  • Manually writing the data model and mapping it to the database with Prisma Migrate

Once the data model is defined, you can generate Prisma Client which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields).


Accessing your database with Prisma Client

Generating Prisma Client

The first step when using Prisma Client is installing its npm package:

npm install @prisma/client

Note that the installation of this package invokes the prisma generate command which reads your Prisma schema and generates the Prisma Client code. The code will be located in node_modules/.prisma/client, which is exported by node_modules/@prisma/client/index.d.ts.

After you change your data model, you'll need to manually re-generate Prisma Client to ensure the code inside node_modules/.prisma/client gets updated:

npx prisma generate

Refer to the documentation for more information about "generating the Prisma client".

Using Prisma Client to send queries to your database

Once the Prisma Client is generated, you can import it in your code and send queries to your database. This is what the setup code looks like.

Import and instantiate Prisma Client

You can import and instantiate Prisma Client as follows:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

or

const { PrismaClient } = require('@prisma/client')

const prisma = new PrismaClient()

Now you can start sending queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return plain old JavaScript objects.

Learn more about the available operations in the Prisma Client docs or watch this demo video (2 min).

Retrieve all User records from the database
// Run inside `async` function
const allUsers = await prisma.user.findMany()
Include the posts relation on each returned User object
// Run inside `async` function
const allUsers = await prisma.user.findMany({
  include: { posts: true },
})
Filter all Post records that contain "prisma"
// Run inside `async` function
const filteredPosts = await prisma.post.findMany({
  where: {
    OR: [{ title: { contains: 'prisma' } }, { content: { contains: 'prisma' } }],
  },
})
Create a new User and a new Post record in the same query
// Run inside `async` function
const user = await prisma.user.create({
  data: {
    name: 'Alice',
    email: '[email protected]',
    posts: {
      create: { title: 'Join us for Prisma Day 2021' },
    },
  },
})
Update an existing Post record
// Run inside `async` function
const post = await prisma.post.update({
  where: { id: 42 },
  data: { published: true },
})

Usage with TypeScript

Note that when using TypeScript, the result of this query will be statically typed so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the Advanced usage of generated types page in the docs.

Community

Prisma has a large and supportive community of enthusiastic application developers. You can join us on Discord and here on GitHub.

Security

If you have a security issue to report, please contact us at [email protected].

Support

Ask a question about Prisma

You can ask questions and initiate discussions about Prisma-related topics in the prisma repository on GitHub.

👉 Ask a question

Create a bug report for Prisma

If you see an error message or run into an issue, please make sure to create a bug report! You can find best practices for creating bug reports (like including additional debugging output) in the docs.

👉 Create bug report

Submit a feature request

If Prisma currently doesn't have a certain feature, be sure to check out the roadmap to see if this is already planned for the future.

If the feature on the roadmap is linked to a GitHub issue, please make sure to leave a 👍 reaction on the issue and ideally a comment with your thoughts about the feature!

👉 Submit feature request

Contributing

Refer to our contribution guidelines and Code of Conduct for contributors.

Tests Status

  • Prisma Tests Status:
    Prisma Tests Status
  • Ecosystem Tests Status:
    Ecosystem Tests Status

blogr-nextjs-prisma's People

Contributors

nikolasburk avatar ruheni avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blogr-nextjs-prisma's Issues

PrismaClient is unable to be run in the browser.

"PrismaClient is unable to be run in the browser."

Any idea why i might be seeing this? Project following this tutorial: https://vercel.com/guides/nextjs-prisma-postgres

Loading the index page produces the error. Commenting out getStaticProps removes it.

Here is my pages/index.tsx:

import { Home } from "src/pages/home";
import prisma from "lib/prisma";
import { GetStaticProps } from "next";

const getStaticProps: GetStaticProps = async () => {
  const users = await prisma.user.findMany({});
  return { props: { users } };
};

export default Home;

This will correct it, however I feel like the separated component is a better quality setup:

import { PrismaClient } from "@prisma/client";
import { GetStaticProps } from "next";

const getStaticProps: GetStaticProps = async () => {
  const prisma = new PrismaClient();
  const users = await prisma.user.findMany({});
  return { props: { users } };
};

Error: insert or update on table "Post" violates foreign key constraint "Post_authorId_fkey"

Error: insert or update on table "Post" violates foreign key constraint "Post_authorId_fkey"
   0: sql_schema_connector::apply_migration::migration_step
           with step=AddForeignKey { foreign_key_id: ForeignKeyId(0) }
             at schema-engine/connectors/sql-schema-connector/src/apply_migration.rs:21
   1: sql_schema_connector::apply_migration::apply_migration
             at schema-engine/connectors/sql-schema-connector/src/apply_migration.rs:10
   2: schema_core::state::SchemaPush
             at schema-engine/core/src/state.rs:436

This happened after migration on step prior to integrating NextAuth. Up until this point had to update these: react@18, react-dom@18, next@13 to be able to install adapter for next-auth.

When run prisma db push all the tables has been created, however the error keeps showing up.

Next-auth/client not found

I think Next-auth change the way it work.

https://github.com/nextauthjs/next-auth#add-react-hook

You have to replace the import with this :

  // import { useSession, signIn, signOut } from "next-auth/client"
  import { useSession, signOut } from "next-auth/react"

So you got the session with this :

  const { data : session, status } = useSession();

And you have to setup a session provider on the top component.

import { AppProps } from "next/app";
import { SessionProvider } from "next-auth/react"

const App = ({ Component, pageProps: { session, ...pageProps } }: AppProps) => {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
};

export default App;

Tell me if i am wrong but it work for me

Typescript error

On building the final version of this example, a Type error is thrown:

./node_modules/.prisma\client\index.d.ts:11:33
Type error: Type expected.

9 | type UnwrapPromise<P extends any> = P extends Promise<infer R> ? R : P

10 | type UnwrapTuple<Tuple extends readonly unknown[]> = {

11 | [K in keyof Tuple]: K extends ${number} ? Tuple[K] extends PrismaPromise ? X : UnwrapPromise<Tuple[K]> : UnwrapPromise<Tuple[K]>
| ^
12 | };
13 |
14 |

error Command failed with exit code 1.

I was able to determine the version of TypeScript was invalid - package.json has:

     "devDependencies": {
    "@types/next-auth": "3.1.14",
    "@types/node": "14.14.6",
    "@types/react": "16.9.56",
    "prisma": "2.25.0",
    "typescript": **"4.0.5"**
  }

It should be:

     "devDependencies": {
    "@types/next-auth": "3.1.14",
    "@types/node": "14.14.6",
    "@types/react": "16.9.56",
    "prisma": "2.25.0",
    "typescript": **"^4.1.0"**
  }

ERROR P1001: Can't reach database serve

I am following the directions to this tutorial, and I am stuck on pushing the database to vercel using the command npx prisma db push but I get this error:

Error: P1001: Can't reach database server at `DBNAME.us-east-1.postgres.vercel-storage.com`:`5432`

Please make sure your database server is running at `DBNAME.us-east-1.postgres.vercel-storage.com`:`5432`.

I have double checked to make sure the variables are correct, I've deleted and rebuilt, and its still the same. I cannot connect vercel database to any local. (Even Postico.)

Property 'prisma' does not exist on type 'Global & typeof globalThis'.ts(2339)

Hello there,

im following your guide here and learn a lot: https://vercel.com/guides/nextjs-prisma-postgres

Of course I'm using newest next.js version and I ran into an issue here in the prisma.ts file:
Property 'prisma' does not exist on type 'Global & typeof globalThis'.ts(2339).

Also I'm not seeing my created post on the front page.

How to fix this? (Im new to next.js excuse me please if It's a really simple question)

Add new Post/Draft not allowed because authentication issues

Hi,
I got help with this issue here:
vercel/next.js#60536
I was getting this error everytime I tries to create a draft:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

And with 808vita helps I had to change this files to work:
draft.tsx

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    const session = await **getServerSession(req, res, authHandler)**;

    if (!session) {
        res.statusCode = 403;
        return { props: { drafts: [] } };
    }

    const drafts = await prisma.post.findMany({
        where: {
            author: { email: session.user.email },
            published: false,
        },
        include: {
            author: {
                select: { name: true },
            },
        },
    });
    return {
        props: { drafts },
    };
};

index.ts

**interface Session {
    user?: {
        email?: string,
    }
}**

export default async function handle(req: any, res: any) {
    const { title, content } = req.body;

    const session: Session = await **getServerSession(req, res, authHandler);**
    if (!session || !session.user.email) {
        res.status(401).json({ error: 'You must be logged in to create a post.' });
        return;
    }

    const result = await prisma.post.create({
        data: {
            title: title,
            content: content,
            author: { connect: { email: session?.user?.email } },
        },
    });
    res.json(result);
}

[...nextauth].ts

export const authHandler: NextAuthOptions = {
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
    ],
    adapter: PrismaAdapter(prisma),
    secret: process.env.SECRET,
}

export default NextAuth(authHandler);

Instead of:

const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;

const options = {
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
    ],
    adapter: PrismaAdapter(prisma),
    secret: process.env.SECRET,
}

The issue was fixed with 808vita's help, but I would like to ask if there is a possibility to update the tutorial instructions, so new devs (as me) wont pass through all this troubles trying to learn more about NextJS

No 'User' record(s) (needed to inline the relation on 'Post' record(s)) was found for a nested connect on one-to-many relation 'PostToUser'.

Hi, I am currently following this tutorial series Step 6. Add new post functionality. However, when I want to make a Draft, I got these error message and I'm stuck here:

Invalid `prisma.post.create()` invocation:
code: 'P2025',
  clientVersion: '2.19.0',
  meta: {
    cause: "No 'User' record(s) (needed to inline the relation on 'Post' record(s)) was found for a nested connect on one-to-many relation 'PostToUser'."
  }
}

And this is my code:
create.tsx

import React, { useState } from 'react'
import Layout from '../components/Layout'
import Router from 'next/router'

const Draft: React.FC = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')

  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault()
    try {
      const body = { title, content }
      await fetch('/api/post', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      await Router.push('/drafts')
    } catch (error) {
      console.error(error)
    }
  }

  return (
      <div>
        <form onSubmit={submitData}>
          <h1>New Draft</h1>
          <input
            autoFocus
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Title"
            type="text"
            value={title}
          />
          <textarea
            cols={50}
            onChange={(e) => setContent(e.target.value)}
            placeholder="Content"
            rows={8}
            value={content}
          />
          <input disabled={!content || !title} type="submit" value="Create" />
          <a className="back" href="#" onClick={() => Router.push('/')}>
            or Cancel
          </a>
        </form>
      </div>
      /// I don't include style tag here.
  )
}

export default Draft

index.ts

import { getSession } from 'next-auth/client'
import prisma from '../../../lib/prisma'

export default async function handle(req, res) {
  const { title, content } = req.body

  const session = await getSession({ req })
  const result = await prisma.post.create({
    data: {
      title: title,
      content: content,
      author: { connect: { email: session?.user?.email } },
    },
  })
  res.json(result)
}

schema.prisma

model Post {
  id        Int     @default(autoincrement()) @id
  title     String
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields: [authorId], references: [id])
  authorId  Int?
}

model User {
  id            Int       @default(autoincrement()) @id
  name          String?
  email         String?   @unique
  emailVerified DateTime? @map(name: "email_verified")
  image         String?
  createdAt     DateTime  @default(now()) @map(name: "created_at")
  updatedAt     DateTime  @updatedAt @map(name: "updated_at")
  posts         Post[]
  @@map(name: "users")
}

Can you help me out? Thank's.

"Collecting page data ...Error: Cannot find module '../lib/prisma'" error - Build error - Can't deploy!

Hi, I'm really trying to finish this tutorial, but there are a few issues in it.

I though I would finish it, I was near, the final steps, THE DEPLOY, BUT I was wrong.

After try the deploy following tutorial instructions I tried build locally.

And I got this error:

npm run build

> [email protected] build
> next build

 ✓ Linting and checking validity of types
   ▲ Next.js 14.0.4
   - Environments: .env

 ✓ Creating an optimized production build
 ✓ Compiled successfully
   Collecting page data  ...Error: Cannot find module '../lib/prisma'
Require stack:
- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/pages/dist/drafts.js- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/require.js
- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/load-components.js
- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/build/utils.js
- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/build/worker.js
- /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/compiled/jest-worker/processChild.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/require-hook.js:55:36
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at mod.require (/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/require-hook.js:65:28)
    at require (node:internal/modules/cjs/helpers:121:18)
    at 1164 (/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/pages/dist/drafts.js:1:1838)
    at o (/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/webpack-runtime.js:1:127)
    at r (/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/pages/dist/drafts.js:1:5274)
    at /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/pages/dist/drafts.js:1:5301 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/.next/server/pages/dist/drafts.js',
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/require.js',
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/server/load-components.js',
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/build/utils.js',
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/build/worker.js',
    '/home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/compiled/jest-worker/processChild.js'
  ]
}

> Build error occurred
Error: Failed to collect page data for /dist/drafts
    at /home/prtpj/Trybe_U/Projetos/tutoriais/react/blogr-nextjs-prisma/node_modules/next/dist/build/utils.js:1220:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}
   Collecting page data  .%

I did a few searchs and I tried:
rm -rf node_modules
npm install
npm install prisma@latest

I found this topics about it:
prisma/prisma#22374
prisma/prisma#21861

Then I tried and updated typescript to 5.2.2, but nothing worked.
Screenshot_347

There are other ways to try fix this issue?

Next v13 support?

After upgrading the final branch to Next.js 13 and Next Auth 4.22.x you are no longer able to make an authenticated post. Sign-in authentication works as expected, however.

Error

[next-auth][error][CLIENT_FETCH_ERROR]

https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

Invalid prisma.post.create() invocation:

{
  data: {
    title: "Test",
    content: "test content",
    author: {
      connect: {
        email: undefined,
?       id?: String
      }
    }
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.