SvelteKit & Prisma Full-Stack CRUD Application

4 min read 1 year ago
Published on Aug 02, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, you will learn how to build a full-stack CRUD application using SvelteKit and Prisma. This guide will walk you through the process of setting up your environment, configuring your database, and implementing create, read, update, and delete functionalities. SvelteKit is a powerful framework for modern web applications, and Prisma simplifies database interactions.

Step 1: Set Up Your Environment

  1. Install Necessary Packages

    • Open your terminal and navigate to your project directory.
    • Run the following command to install Prisma and the Prisma Client:
      npm install prisma @prisma/client
      
  2. Initialize Prisma

    • After installing, initialize Prisma with:
      npx prisma init
      
    • This command creates a prisma folder with a schema.prisma file.
  3. Configure Database

    • Open schema.prisma and set the provider to SQLite:
      datasource db {
        provider = "sqlite"
        url      = "file:./dev.sqlite"
      }
      

Step 2: Define Your Data Model

  1. Create a Model

    • In schema.prisma, define your data model for articles:
      model Article {
        id      Int     @id @default(autoincrement())
        title   String
        content String
      }
      
  2. Push the Database Changes

    • Open your terminal and run:
      npx prisma db push
      
    • This command creates the SQLite database and the Article table.

Step 3: Set Up Prisma Client

  1. Create Prisma Client File
    • Create a new directory called lib/server, and within it, create a file named prisma.ts.
    • Add the following code to handle Prisma Client:
      import { PrismaClient } from '@prisma/client';
      
      const globalPrisma = global as any;
      
      export const prisma =
        globalPrisma.prisma ||
        new PrismaClient();
      
      if (process.env.NODE_ENV !== 'production') {
        globalPrisma.prisma = prisma;
      }
      

Step 4: Implement Create Functionality

  1. Create Action for Adding Articles

    • Create a new file named +page.server.ts in your routes folder.
    • Add the following code for creating articles:
      import { prisma } from '../lib/server/prisma';
      
      export const actions = {
        createArticle: async ({ request }) => {
          const formData = await request.formData();
          const title = formData.get('title') as string;
          const content = formData.get('content') as string;
      
          try {
            await prisma.article.create({ data: { title, content } });
            return { status: 201 };
          } catch (error) {
            console.error(error);
            return { status: 500 };
          }
        }
      };
      
  2. Update Your Form

    • Ensure your form calls the createArticle action by setting its method to POST.

Step 5: Implement Read Functionality

  1. Load Articles from Database

    • In the same +page.server.ts file, add a load function:
      export const load = async () => {
        const articles = await prisma.article.findMany();
        return { articles };
      };
      
  2. Display Articles

    • In your component, loop through the articles data and display it:
      {#each articles as article}
        <h2>{article.title}</h2>
        <p>{article.content}</p>
      {/each}
      

Step 6: Implement Delete Functionality

  1. Create Delete Action

    • Add a new delete action in your +page.server.ts file:
      export const actions = {
        deleteArticle: async ({ request }) => {
          const url = new URL(request.url);
          const id = url.searchParams.get('id');
      
          if (!id) return { status: 400 };
      
          try {
            await prisma.article.delete({ where: { id: Number(id) } });
            return { status: 200 };
          } catch (error) {
            console.error(error);
            return { status: 500 };
          }
        }
      };
      
  2. Link Delete Button to Action

    • Wrap your delete button in a form with the delete action.

Step 7: Implement Update Functionality

  1. Create Update Route

    • Create a new route file for editing articles, e.g., article/[id]/+page.server.ts.
    • Load the article details:
      export const load = async ({ params }) => {
        const article = await prisma.article.findUnique({ where: { id: Number(params.id) } });
        return { article };
      };
      
  2. Create Update Form

    • Populate the form with the existing article details and set the action for updating:
      export const actions = {
        updateArticle: async ({ request, params }) => {
          const formData = await request.formData();
          const title = formData.get('title') as string;
          const content = formData.get('content') as string;
      
          try {
            await prisma.article.update({
              where: { id: Number(params.id) },
              data: { title, content }
            });
            return { status: 200 };
          } catch (error) {
            console.error(error);
            return { status: 500 };
          }
        }
      };
      

Conclusion

You have successfully built a full-stack CRUD application using SvelteKit and Prisma. You set up the environment, defined your data model, and implemented create, read, update, and delete functionalities. Next steps could include adding user authentication, deploying your application, or exploring more advanced features of SvelteKit and Prisma. Happy coding!