Full-stack Web Technologies

CHAPTER 1
Setting Up the Database

  1. Create a project with

    bun init .
    
  2. Edit package.json: version, description, etc.

  3. Install packages:

    bun i express morgan cors
    bun i -D @types/express @types/cors @types/morgan prisma
    
  4. Initialize Prisma:

    bunx prisma init --datasource-provider sqlite
    
  5. Check that .gitignore contains .env (it should with Bun).

  6. Edit schema.prisma to add the Forum entity:

    model Forum {
       id        Int      @id      @default(autoincrement())
       name      String   @unique
       createdAt DateTime @default(now())
    }
    
  7. Push the schema.prisma to the database to apply changes:

    bunx prisma db push
    
  8. Open Prisma Studio (bunx prisma studio) and add a couple of Forums to check.

  9. Add two more entities: User and Message.

    model User {
       userId    Int       @id @default(autoincrement()) @map("id")
       nick      String    @unique
       fullName  String?
       createdAt DateTime  @default(now())
       admin     Boolean   @default(false)
       messages  Message[]
    }
    
    model Message {
       id      Int    @id @default(autoincrement())
       text    String
       userId  Int
       User    User   @relation(fields: [userId], references: [userId])
       forumId Int
       Forum   Forum  @relation(fields: [forumId], references: [forumId])
    }
    
  10. Push changes in the schema to the database.

  11. Create a prisma/seed.ts file and add test data that you would like to have in the initial database (after a reset).

  12. Add the "prisma" section to the package.json file to invoke the seeding process:

    {
      // ...
      "prisma": {
        "seed": "bun prisma/seed.ts"
      }
    }
    
  13. Now reset the database to check that it can be re-created from scratch:

    rm prisma/dev.db
    bunx prisma db push
    bunx prisma db seed