# Prisma Crud Full

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FJvEN5ZneKXtJIiUYKKww%2Fimage.png?alt=media&#x26;token=98c27923-436a-4cb9-9da1-9b063ba5ca96" alt=""><figcaption></figcaption></figure>

### Example 1

{% file src="<https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2Ff7KgiFW57DBXkjPRGGFM%2Fprisma.zip?alt=media&token=8c0a5b9f-2518-4365-976e-a388565a78da>" %}

package.json

```json
{
  "name": "prisma",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "description": "",
  "dependencies": {
    "@prisma/client": "^6.6.0",
    "@types/cors": "^2.8.17",
    "@types/express": "^5.0.1",
    "@types/express-graphql": "^0.8.2",
    "@types/graphql": "^14.2.3",
    "@types/lodash": "^4.17.16",
    "cors": "^2.8.5",
    "dotenv": "^16.5.0",
    "express": "^5.1.0",
    "express-graphql": "^0.12.0",
    "fs": "^0.0.1-security",
    "graphql": "^15.10.1",
    "graphql-yoga": "^5.13.4",
    "lodash": "^4.17.21",
    "nodemon": "^3.1.10",
    "path": "^0.12.7"
  },
  "devDependencies": {
    "@types/node": "^22.15.2",
    "prisma": "^6.6.0"
  },
  "prisma": {
    "seed": "ts-node prisma/seed"
  }
}

```

.env

```properties
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
# DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
DATABASE_URL="mysql://root@localhost:3306/prisma"
```

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: {
      published: true
    },
    include: {
      author: true
    }
  })
  res.json(posts)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

prisma\seed.ts

```typescript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient();
const userData = [
  {
    name: 'Lionel 1',
    email: 'lionel1@prisma.io',
    posts: {
      create: [
        {
          title: 'Post Lionel 1',
          content: 'https://slack.prisma.io',
          published: true,
        },
      ],
    },
  },
  {
    name: 'Lionel 2',
    email: 'lionel2@prisma.io',
    posts: {
      create: [
        {
          title: 'Post Lionel 2.1',
          content: 'https://slack.prisma.io',
          published: true,
        },
        {
          title: 'Post LIonel 2.2',
          content: 'https://pris.ly/youtube',
        },
      ],
    },
  },
];
async function main() {
  console.log(`Start seeding ...`);
  for (const u of userData) {
    const user = await prisma.user.create({
      data: u,
    })
    console.log(`Created user with id: ${user.id}`)
  }
  console.log(`Seeding finished.`)
}
main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

```

Hoặc

prisma\seed.ts

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2F0HrDqHGOpswEybo5nctI%2Fimage.png?alt=media&#x26;token=a60def0b-abe2-422e-8d88-2a5e112d2d52" alt=""><figcaption></figcaption></figure>

```typescript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient();
const userData = [
  {
    name: 'Alice Johnson',
    email: 'alice@example.com',
    posts: {
      create: [
        {
          title: 'Getting Started with Prisma',
          content: 'A comprehensive guide to using Prisma in your projects',
          published: true,
          viewCount: 150,
        },
        {
          title: 'TypeScript Best Practices',
          content: 'Learn how to write better TypeScript code',
          published: true,
          viewCount: 89,
        },
      ],
    },
  },
  {
    name: 'Bob Smith',
    email: 'bob@example.com',
    posts: {
      create: [
        {
          title: 'Database Optimization Tips',
          content: 'How to optimize your database queries for better performance',
          published: true,
          viewCount: 210,
        },
        {
          title: 'Draft: Advanced SQL Techniques',
          content: 'Coming soon: Advanced SQL techniques for developers',
          published: false,
          viewCount: 0,
        },
      ],
    },
  },
  {
    name: 'Carol Williams',
    email: 'carol@example.com',
    posts: {
      create: [
        {
          title: 'Building REST APIs with Node.js',
          content: 'A step-by-step guide to creating RESTful APIs',
          published: true,
          viewCount: 175,
        },
      ],
    },
  },
];
async function main() {
  console.log(`Start seeding ...`);
  // Create users with their posts
  for (const u of userData) {
    const user = await prisma.user.create({
      data: u,
    });
    console.log(`Created user with id: ${user.id}`);
  }
  // Create some orphaned posts (without authors)
  await prisma.post.createMany({
    data: [
      {
        title: 'Anonymous Post 1',
        content: 'This post has no author',
        published: true,
        viewCount: 45,
      },
      {
        title: 'Anonymous Post 2',
        content: 'Another post without an author',
        published: false,
        viewCount: 0,
      },
    ],
  });
  console.log(`Seeding finished.`);
}
main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

```

prisma\schema.prisma

```prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}
model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

```

### Example 2

src\index.js

```javascript
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
  const device = await prisma.device.create({
    data: {
      name: "Alice 2",
      data: { key: "value 2" },
    },
  });
  console.log(device);
}
main()
  .catch(async (e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

```

.env

```properties
DATABASE_URL="mysql://root@localhost:3306/prisma"
```

package.json

```json
{
  "name": "graph",
  "version": "1.0.0",
  "main": "src/index.js",
  "type": "module",
  "scripts": {
    "dev": "nodemon src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "@prisma/client": "^6.2.1",
    "dotenv": "^16.4.7",
    "express": "^4.21.2",
    "express-graphql": "^0.12.0",
    "fs": "^0.0.1-security",
    "graphql": "^16.10.0",
    "graphql-yoga": "^5.10.9",
    "lodash": "^4.17.21",
    "nodemon": "^3.1.9",
    "path": "^0.12.7"
  }
}

```

prisma\schema.prisma

```prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
model Device {
  id   Int     @id @default(autoincrement())
  name String
  data Json
}

```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FArrYhgIsZBbhSYrj8iWT%2Fimage.png?alt=media&#x26;token=be3fc4ef-a4d9-4a65-955a-5091b93fe1bd" alt=""><figcaption></figcaption></figure>

### Example 2 Full back-end

### Part 1. Create database example

package.json

```json
{
  "dependencies": {
    "@prisma/client": "^6.2.1",
    "cors": "^2.8.5",
    "express": "^4.21.2"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^5.0.0",
    "@types/node": "^22.10.5",
    "@types/typescript": "^2.0.0",
    "prisma": "^6.2.1",
    "ts-node": "^10.9.2",
    "typescript": "^5.7.3"
  },
  "prisma": {
    "seed": "ts-node prisma/seed.ts"
  }
}

```

### — npx tsc --init read file typescript

```
npx tsc --init
```

### — npx prisma

```
npx prisma
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FXadjfcCKAH89oOIzrDod%2Fimage.png?alt=media&#x26;token=9416dfb4-aa65-4765-b770-603aa336fb40" alt=""><figcaption></figcaption></figure>

### — npx prisma init

```
npx prisma init
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2F1zLEnQiEjXNraAH7QraS%2Fimage.png?alt=media&#x26;token=898be6d3-cdd9-41c3-9dc7-76c4a250cbf2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FNxFbpY3ZpM97EezqSUM9%2Fimage.png?alt=media&#x26;token=0f9f3c41-b782-4262-a039-710280baa76f" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FjASpbjI5oZHivfdmABLh%2Fimage.png?alt=media&#x26;token=6fdecbce-8ff6-40f6-b6a9-b3d13a90c9aa" alt=""><figcaption></figcaption></figure>

### — prisma db push

```
prisma db push
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2Fu0ZXPQNTqNSOEMud0kCW%2Fimage.png?alt=media&#x26;token=d5f6a432-310b-43e6-9328-f761131bf2a2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FTI9a90tlAHdHPtI9sL1u%2Fimage.png?alt=media&#x26;token=c92f5431-7230-409a-b8b1-795c6aadcf89" alt=""><figcaption></figcaption></figure>

prisma\seed.ts

```typescript
import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient();
const userData: Prisma.UserCreateInput[] = [
  {
    name: 'Lionel 1',
    email: 'lionel1@prisma.io',
    posts: {
      create: [
        {
          title: 'Post Lionel 1',
          content: 'https://slack.prisma.io',
          published: true,
        },
      ],
    },
  },
  {
    name: 'Lionel 2',
    email: 'lionel2@prisma.io',
    posts: {
      create: [
        {
          title: 'Post Lionel 2.1',
          content: 'https://slack.prisma.io',
          published: true,
        },
        {
          title: 'Post LIonel 2.2',
          content: 'https://pris.ly/youtube',
        },
      ],
    },
  },
];
async function main() {
  console.log(`Start seeding ...`);
  for (const u of userData) {
    const user = await prisma.user.create({
      data: u,
    })
    console.log(`Created user with id: ${user.id}`)
  }
  console.log(`Seeding finished.`)
}
main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FQZ2nOg7ALjeHp2javGhi%2Fimage.png?alt=media&#x26;token=ad4887a3-033c-4aa1-ae33-6b039fa12d7f" alt=""><figcaption></figcaption></figure>

### — yarn prisma db seed

```
yarn prisma db seed
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FUuCDMdBh1Fp86N6kt3J6%2Fimage.png?alt=media&#x26;token=6fa23116-0984-44f6-be61-476872e7e1fb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2Fk2yhqqYQCPiH9HcXI48Q%2Fimage.png?alt=media&#x26;token=c0bd81d7-e8cf-410e-8019-a10f3b08aec2" alt=""><figcaption></figcaption></figure>

### Part 2 Back-end

### — package.json add scripts

```
"scripts": {
    "dev": "ts-node src/index.ts"
},
```

### — npx prisma db push --force-reset

Khi muốn reset lại dữ liệu&#x20;

cập nhật lại prisma\schema.prisma trong quá trình phát triển

```
npx prisma db push --force-reset
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2F2qMFCF30afZ9NM3pGDpZ%2Fimage.png?alt=media&#x26;token=4aca4815-1e8c-4a76-887d-c9a51471164d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2Fp8T6hq42BEAu2jkTKWE6%2Fimage.png?alt=media&#x26;token=e8c6cdfa-9434-4747-8662-5a6527fa61f5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FZLT2CnijZcKg2nLCci6d%2Fimage.png?alt=media&#x26;token=a2bdc64f-44a6-4f5d-8cf3-4ee1a23e833a" alt=""><figcaption></figcaption></figure>

```typescript
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "sqlite"
  url      = "file:./dev.sqlite"
}
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  Post  Post[]
}
model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

```

### — Read database

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FOBuhwgqLqvi4ylTgMbQo%2Fimage.png?alt=media&#x26;token=c4f42d23-7a43-4840-86bb-81048643dcba" alt=""><figcaption></figcaption></figure>

### — Create Post

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FQKXy8ilOHpY9EY8qHDwr%2Fimage.png?alt=media&#x26;token=a54c4322-5c6a-4f3d-97e4-25fb6e89bd71" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2Fs8Na4wbV8HpAUFsqxXeV%2Fimage.png?alt=media&#x26;token=5a282d29-79ea-4198-81db-ea4433e2f209" alt=""><figcaption></figcaption></figure>

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: false,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

### — Get Post&#x20;

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
})
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FCgKcAXxU6HMBr1fIFilZ%2Fimage.png?alt=media&#x26;token=02360595-0435-4021-87b2-4df82c5a5aeb" alt=""><figcaption></figcaption></figure>

### — Delete Post

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
})
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
})
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FqvcmN1563c5yH33MCk1Y%2Fimage.png?alt=media&#x26;token=13494cc6-2f42-41c1-bf19-10407d36279e" alt=""><figcaption></figcaption></figure>

### — Update Post

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FhYaoLynJysQLcdBxNn2u%2Fimage.png?alt=media&#x26;token=6a263e65-56fe-40ca-843c-c42392137957" alt=""><figcaption></figcaption></figure>

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { 
      title,
      content,
      viewCount,
      published: true 
    },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

— Update Status Post

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FXFqvuRMjfUwgBWBBTn3c%2Fimage.png?alt=media&#x26;token=783e3ebf-b9e4-4343-8665-a0845079f9d7" alt=""><figcaption></figcaption></figure>

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { 
      title,
      content,
      viewCount,
      published: true 
    },
  })
  res.json(post)
});
app.put('/publish/:id', async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { published: true },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

### — Create User

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { 
      title,
      content,
      viewCount,
      published: true 
    },
  })
  res.json(post)
});
app.put('/publish/:id', async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { published: true },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
});
// Part 4
app.post(`/user`, async (req, res) => {
  const result = await prisma.user.create({
    data: {
      ...req.body,
    },
  })
  res.json(result)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FIHjGJANzZEGJu1HKtXbP%2Fimage.png?alt=media&#x26;token=5482e7d4-39d4-4c0c-80c1-7cd0b3efb7fa" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FAGjJd5uDpbbq1uCM1igi%2Fimage.png?alt=media&#x26;token=49caa382-c7d8-4c15-8673-40ca7a179b65" alt=""><figcaption></figcaption></figure>

### — Get Users

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: {
      title,
      content,
      viewCount,
      published: true
    },
  })
  res.json(post)
});
app.put('/publish/:id', async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { published: true },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
});
// Part 4
app.post(`/user`, async (req, res) => {
  const result = await prisma.user.create({
    data: {
      ...req.body,
    },
  })
  res.json(result)
});
app.get(`/users`, async (req, res) => {
  const result = await prisma.user.findMany()
  res.json(result)
});
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2F37FThD7Ll6mHVOFuhaX3%2Fimage.png?alt=media&#x26;token=5dc405de-76ad-46ff-939d-e41963601391" alt=""><figcaption></figcaption></figure>

### — filterPosts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { 
      title,
      content,
      viewCount,
      published: true 
    },
  })
  res.json(post)
});
app.put('/publish/:id', async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { published: true },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
});
// Part 4
app.post(`/user`, async (req, res) => {
  const result = await prisma.user.create({
    data: {
      ...req.body,
    },
  })
  res.json(result)
});
// Part 5
app.get('/filterPosts', async (req, res) => {
  const { title } = req.body;
  const filteredPosts = await prisma.post.findMany({
    where: {
      OR: [
        {
          title: {
            contains: title,
          },
        }
      ],
    },
  })
  res.json(filteredPosts)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

#### Or

src\index.ts

```typescript
// Part 1
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import cors from 'cors';
import express from 'express';
const app = express();
app.use(express.json())
app.use(cors());
// Part 2
app.get('/feed', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: true }
  })
  res.json(posts)
});
app.get('/drafts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: false },
    include: { author: true }
  })
  res.json(posts)
});
app.get(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.findUnique({
    where: {
      id: Number(id),
    },
    include: { author: true }
  })
  res.json(post)
});
app.delete(`/post/:id`, async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.delete({
    where: {
      id: Number(id),
    },
  })
  res.json(post)
});
app.put('/post/:id', async (req, res) => {
  const { id } = req.params;
  const { title, content, viewCount } = req.body;
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: {
      title,
      content,
      viewCount,
      published: true
    },
  })
  res.json(post)
});
app.put('/publish/:id', async (req, res) => {
  const { id } = req.params
  const post = await prisma.post.update({
    where: { id: Number(id) },
    data: { published: true },
  })
  res.json(post)
});
// Part 3
app.post(`/post`, async (req, res) => {
  const { title, content, authorEmail } = req.body
  const result = await prisma.post.create({
    data: {
      title,
      content,
      published: true,
      author: { connect: { email: authorEmail } },
    },
  })
  res.json(result)
});
// Part 4
app.post(`/user`, async (req, res) => {
  const result = await prisma.user.create({
    data: {
      ...req.body,
    },
  })
  res.json(result)
});
// Part 5
app.get('/filterPosts', async (req, res) => {
  const { title: searchTitle, content: searchContent } = req.body;
  const filteredPosts = await prisma.post.findMany({
    where: {
      OR: [
        {
          title: {
            contains: searchTitle,
          },
        },
        {
          content: {
            contains: searchContent
          },
        }
      ],
    },
  })
  res.json(filteredPosts)
})
const server = app.listen(3001, () =>
  console.log(
    '🚀 Server ready at: http://localhost:3001',
  ),
);
```

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FMyQA5Nr9fA0CJRAF7YNJ%2Fimage.png?alt=media&#x26;token=a78a6fea-9792-4966-8e77-d0d0ccab99c2" alt=""><figcaption></figcaption></figure>

### Part 3 Front-end

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FfoMSoc3ogmFwLJgrCXhT%2Fimage.png?alt=media&#x26;token=c71f8923-31ab-4543-a5fa-7380a7b7c6d8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FvB4fcr0y4wnWed6w5ZtF%2Fimage.png?alt=media&#x26;token=2de04106-6413-4d1c-97d5-5768e4428b36" alt=""><figcaption></figcaption></figure>

package.json

```json
{
  "name": "crudfront",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "15.1.4",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-markdown": "^9.0.3"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "postcss": "^8",
    "tailwindcss": "^3.4.1",
    "typescript": "^5"
  }
}

```

pages/\_app.tsx

```typescript
import "@/styles/globals.css";
import type { AppProps } from "next/app";
export default function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}
```

pages/\_document.tsx

```typescript
import { Html, Head, Main, NextScript } from "next/document";
import Header from '@/components/Header';
export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Header />
        <div className="container px-2 m-auto">
          <Main />
          <NextScript />
        </div>
      </body>
    </Html>
  );
}

```

pages\create.tsx

```typescript
import React, { useState } from 'react'
import Router from 'next/router'
const Draft: React.FC = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [authorEmail, setAuthorEmail] = useState('')
  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault()
    try {
      const body = { title, content, authorEmail }
      await fetch(`http://localhost:3001/post`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      await Router.push('/drafts')
    } catch (error) {
      console.error(error)
    }
  }
  return (
    <div>
      <h1 className='text-xl mb-2'>Create Draft</h1>
      <form
        onSubmit={submitData}>
        <input
          autoFocus
          onChange={e => setTitle(e.target.value)}
          placeholder="Title"
          type="text"
          value={title}
          className='mb-5 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md sm:text-sm focus:ring-1 invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500'
        />
        <br />
        <input
          onChange={e => setAuthorEmail(e.target.value)}
          placeholder="Author (email address)"
          type="text"
          value={authorEmail}
          className='mb-5 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md sm:text-sm focus:ring-1 invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500'
        />
        <br />
        <textarea
          cols={50}
          onChange={e => setContent(e.target.value)}
          placeholder="Content"
          rows={8}
          value={content}
          className='mb-5 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md sm:text-sm focus:ring-1 invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500'
        />
        <br />
        <input
          disabled={!content || !title || !authorEmail}
          type="submit"
          value="Create"
          className='bg-red-500 hover:bg-red-700 px-5 py-2 text-sm leading-5 rounded-full font-semibold text-white'
        />
        <a className="back" href="#" onClick={() => Router.push('/')}>
          or Cancel
        </a>
      </form>
    </div>
  )
}
export default Draft

```

pages\drafts.tsx

```typescript
import React from "react"
import { GetServerSideProps } from "next"
import Post, { PostProps } from "@/components/Post"
type Props = {
  drafts: PostProps[]
}
const Drafts: React.FC<Props> = (props) => {
  return (
    <div className="page">
      <h1 className='text-xl mb-2'>Drafts</h1>
      <main>
        {props.drafts.map((post) => (
          <div key={post.id} className="post">
            <Post post={post} />
          </div>
        ))}
      </main>
    </div>
  )
}
export const getServerSideProps: GetServerSideProps = async () => {
  const res = await fetch("http://localhost:3001/drafts")
  const drafts = await res.json()
  return {
    props: { drafts },
  }
}
export default Drafts

```

pages\index.tsx

```typescript
import React from 'react'
import { GetServerSideProps } from 'next'
import Post, { PostProps } from '@/components/Post'
type Props = {
  feed: PostProps[]
}
const Blog: React.FC<Props> = props => {
  return (
    <div className="page">
      <h1 className='text-xl mb-2'>My Blog</h1>
      <main>
        {props.feed.map(post => (
          <div key={post.id} className="post shadow mb-4 p-2">
            <Post post={post} />
          </div>
        ))}
      </main>
    </div>
  )
}
export const getServerSideProps: GetServerSideProps = async () => {
  const res = await fetch('http://localhost:3001/feed')
  const feed = await res.json()
  return {
    props: { feed },
  }
}
export default Blog

```

pages\signup.tsx

```typescript
import React, { useState } from 'react'
import Router from 'next/router'
const SignUp: React.FC = () => {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault()
    try {
      const body = { name, email }
      await fetch(`http://localhost:3001/user`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      await Router.push('/')
    } catch (error) {
      console.error(error)
    }
  }
  return (
    <div className="page">
      <h1 className='text-xl mb-2'>Signup user</h1>
      <form
        onSubmit={submitData}
        >
        <input
          autoFocus
          onChange={e => setName(e.target.value)}
          placeholder="Name"
          type="text"
          value={name}
          className='mb-5 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md sm:text-sm focus:ring-1 invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500'
        />
        <br/>
        <input
          onChange={e => setEmail(e.target.value)}
          placeholder="Email address"
          type="text"
          value={email}
          className='mb-5 px-3 py-2 bg-white border shadow-sm border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md sm:text-sm focus:ring-1 invalid:border-pink-500 invalid:text-pink-600 focus:invalid:border-pink-500 focus:invalid:ring-pink-500'
        />
        <br/>
        <input
          disabled={!name || !email}
          type="submit"
          value="Signup"
          className='bg-red-500 hover:bg-red-700 px-5 py-2 text-sm leading-5 rounded-full font-semibold text-white'
        />
        <a className="back" href="#" onClick={() => Router.push('/')}>
          or Cancel
        </a>
      </form>
    </div>
  )
}
export default SignUp
```

pages\p\\\[id].tsx

```typescript
import React from 'react'
import { GetServerSideProps } from 'next'
import ReactMarkdown from 'react-markdown'
import Router from 'next/router'
import { PostProps } from '../../components/Post'
async function publish(id: number): Promise<void> {
  await fetch(`http://localhost:3001/publish/${id}`, {
    method: 'PUT',
  })
  await Router.push('/')
}
async function destroy(id: number): Promise<void> {
  await fetch(`http://localhost:3001/post/${id}`, {
    method: 'DELETE',
  })
  await Router.push('/')
}
const Post: React.FC<PostProps> = props => {
  let title = props.title
  if (!props.published) {
    title = `${title} (Draft)`
  }
  return (
    <div>
      <h1 className='text-xl mb-2'>Post Detail</h1>
      <h2>{title}</h2>
      <p>By {props?.author?.name || 'Unknown author'}</p>
      <ReactMarkdown>{props.content}</ReactMarkdown>
      {!props.published && (
        <button onClick={() => publish(props.id)}>
          Publish
        </button>
      )}
      <button className='bg-red-500 hover:bg-red-700 px-5 py-2 text-sm leading-5 rounded-full font-semibold text-white' onClick={() => destroy(props.id)}>
        Delete
      </button>
    </div>
  )
}
export const getServerSideProps: GetServerSideProps = async (context) => {
  const id = context?.params?.id
  const res = await fetch(`http://localhost:3001/post/${id}`)
  const data = await res.json()
  return { props: { ...data } }
}
export default Post

```

components\Header.tsx

```typescript
'use client'
import React from 'react'
import Link from 'next/link'
const Header: React.FC = () => {
  return (
    <nav className='flex justify-between bg-black text-white py-4 px-2'>
      <div className="flex gap-2" >
        <Link href="/" className="bold hover:text-emerald-400">
          Blog
        </Link>
        <Link href="/drafts" className="bold hover:text-emerald-400">
          Drafts
        </Link>
      </div>
      <div className="flex gap-2">
        <Link href="/signup" className="bold hover:text-emerald-400">
          Signup
        </Link>
        <Link href="/create" className="bold hover:text-emerald-400">
          Create draft
        </Link>
      </div>
    </nav>
  )
}
export default Header

```

components\Post.tsx

```typescript
import React from 'react'
import Router from 'next/router'
import ReactMarkdown from "react-markdown";
export type PostProps = {
  id: number;
  title: string;
  author: {
    name: string;
  }
  content: string;
  published: boolean;
}
const Post: React.FC<{ post: PostProps }> = ({ post }) => {
  const authorName = post.author ? post.author.name : 'Unknown author'
  return (
    <div onClick={() => Router.push('/p/[id]', `/p/${post.id}`)}>
      <h2>{post.title}</h2>
      <small>By {authorName}</small>
      <ReactMarkdown children={post.content} />
    </div>
  )
}
export default Post
```

### Part 4 Connect mysql&#x20;

.env

```properties
DATABASE_URL="mysql://root@localhost:3306/crudback"
```

```
prisma db push
```

prisma\schema.prisma

```prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts  Post[]
}
model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  viewCount Int      @default(0)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  author      User?    @relation(fields: [authorId], references: [id])
  authorId    Int?
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/javascript/advanced/prisma-crud-full.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
