code snippets

Generic CRUD() Starter Template - Next.js

... a VERY generic starting template for Create, Read, Update and Delete operations in a Next.js template.


How This Works: The entire application is a minimalist approach to a starting CRUD() application.


  1. 1. Download the application from Github.
  2. 2. Unzip/unpackage the download then run
          npm install
  3. 3. Install Prisma into your project. Prisma is an Object Relational Mapping utility (ORM) that helps type and develop your database interactions.
          npm install Prisma -D
  4. 4. Initialize Prisma with Sqlite
          npx prisma init —datasource-provider sqlite
    This will create a prisma directory in the root of your application and attach a sqlite database to your project.
  5. 5. Inside of the prisma directory that was just created there is a schema.prisma file. In schema.prisma, in the datasource db section change the url to “file:app.db”.
  6. 6. Also in schema.prisma add the Product model beneath the datasource information. In the end your schema.prisma file should look like this:

    1// This is your Prisma schema file,
    2// learn more about it in the docs: https://pris.ly/d/prisma-schema
    3
    4generator client {
    5  provider = "prisma-client-js"
    6}
    7
    8datasource db {
    9  provider = "sqlite"
    10  url      = "file:app.db"
    11}
    12
    13model Product {
    14  id    Int       @id @default(autoincrement())
    15  title String
    16  price Int
    17  description String?
    18}
  7. 7. You have to run a "migration" to create the database table(s) from the schema
          npx prisma migrate dev —name init
    The above command creates a migration file, executes a migration against your db and generates the prisma client which interacts with your database.
  8. 8. You have to generate a file, (call it prisma-db.ts) in /app directory.
    Paste the following code into the prisma-db.ts file and it will generate all of the CRUD() methods that will act on your database. There’s even a seedProducts() function that will automatically pre-populate the database in case there aren’t any records.

    1import { PrismaClient } from "@prisma/client";
    2const prisma = new PrismaClient();
    3
    4const seedProducts = async () => {
    5    const count = await prisma.product.count();
    6    if (count === 0) {
    7        await prisma.product.createMany({
    8            data: [
    9                { title: "Product 1", price: 500, description: "Description 1" },
    10                { title: "Product 2", price: 700, description: "Description 2" },
    11                { title: "Product 3", price: 1000, description: "Description 3" },
    12            ],
    13        });
    14    }
    15};
    16
    17// Run seed if needed
    18seedProducts();
    19
    20export async function getProducts(query?: string) {
    21    await new Promise((resolve) => setTimeout(resolve, 1500));
    22    if (query) {
    23        return prisma.product.findMany({
    24            where: {
    25                OR: [
    26                    { title: { contains: query } },
    27                    { description: { contains: query } },
    28                ],
    29            },
    30        });
    31    }
    32    return prisma.product.findMany();
    33}
    34
    35export async function getProduct(id: number) {
    36    await new Promise((resolve) => setTimeout(resolve, 1500));
    37    return prisma.product.findUnique({
    38        where: { id },
    39    });
    40}
    41
    42export async function addProduct(
    43    title: string,
    44    price: number,
    45    description: string
    46) {
    47    await new Promise((resolve) => setTimeout(resolve, 1500));
    48    return prisma.product.create({
    49        data: { title, price, description },
    50    });
    51}
    52
    53export async function updateProduct(
    54    id: number,
    55    title: string,
    56    price: number,
    57    description: string
    58) {
    59    await new Promise((resolve) => setTimeout(resolve, 1500));
    60    return prisma.product.update({
    61        where: { id },
    62        data: { title, price, description },
    63    });
    64}
    65
    66export async function deleteProduct(id: number) {
    67    await new Promise((resolve) => setTimeout(resolve, 1500));
    68    return prisma.product.delete({
    69        where: { id },
    70    });
    71}
  9. 9. Finally, you might want to add your database to your .gitignore file.

    #database
    /prisma/app.db