An Express template using Prisma with Postgresql
- Create two enviroment files in the root of the project:
.env
.env.test
It must contain the following variable:
An example would be:DATABASE_URL=postgresql://<USERNAME>:<PASSWORD>@<HOST>:<PORT>/<DATABASE_NAME>?schema=public
Keep in mind that the test database connection url (inDATABASE_URL=postgresql://postgres:postgres@localhost:5432/template_dev?schema=public
.env.test
) must have a different database name than the one in your.env
file. - Install the project dependencies:
yarn install
- Add a model to the schema in
src/prisma/schema.prisma
:All models have to be written in the same file (model Hello { id String @id @default(uuid()) @db.Uuid name String @db.VarChar createdAt DateTime @db.Timestamp(6) @default(now()) updatedAt DateTime @db.Timestamp(6) @updatedAt }
schema.prisma
), so to keep a sort of order in your models, it's recommended that you write them in alphabetical order. To format yourschema.prisma
, pressOpt
+Shift
+F
on Mac andAlt
+Shift
+F
on Windows. Then, run this command to save the Prisma types in yournode_modules
folder:yarn prisma:generate
- Run a migration to reflect changes to your schema in the database:
If you want to forcefully synchronize your schema into a database without running migrations, you can do:
yarn db:migrate --name your-migration-name
If you want to reset your database, run:yarn db:sync:force
More information about Prisma and migrations in their docs. Never edit your migration files; it's always better to just create new migrations.yarn db:reset
- Apply seeds to your database:
yarn db:seed
- Now you can create a controller that interacts with your model. Create a new route file inside the
src/handlers/api/routes
folder; then add a reference to that file in thesrc/handlers/api/routes/index.js
file, creating the route itself. At the same time, create the necessary logic for each route in thesrc/handlers/api/controllers
folder, creating a file for each route. You should also use the services folder to create all the functions that interact with the database directly, later importing each of these files into one ore more controllers. If you also want to make a view, you should follow the same process in thesrc/handlers/ssr
folder. For this, create a new folder insidesrc/views
with the name of the route and add all the views related to each route there. - Finally, run your app with the command:
Or, if you want your app to listen to changes, run:
yarn start
yarn dev
Open a database visualizer:
npx prisma studio
Pull the schema from an existing database into an empty schema:
npx db pull