Skip to content

Commit 2d16731

Browse files
authored
feat: add example with bun (#8287)
* feat: add example with bun.js * feat: add new example * fix: clean nits * fix: resolve coderabbit nits
1 parent 68c04c6 commit 2d16731

18 files changed

Lines changed: 826 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
DATABASE_URL=""
2+
DIRECT_URL=""
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
2+
3+
# Logs
4+
5+
logs
6+
_.log
7+
npm-debug.log_
8+
yarn-debug.log*
9+
yarn-error.log*
10+
lerna-debug.log*
11+
.pnpm-debug.log*
12+
13+
index
14+
prisma/migrations
15+
# Caches
16+
17+
.cache
18+
19+
# Diagnostic reports (https://nodejs.org/api/report.html)
20+
21+
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
22+
23+
# Runtime data
24+
25+
pids
26+
_.pid
27+
_.seed
28+
*.pid.lock
29+
30+
# Directory for instrumented libs generated by jscoverage/JSCover
31+
32+
lib-cov
33+
34+
# Coverage directory used by tools like istanbul
35+
36+
coverage
37+
*.lcov
38+
39+
# nyc test coverage
40+
41+
.nyc_output
42+
43+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
44+
45+
.grunt
46+
47+
# Bower dependency directory (https://bower.io/)
48+
49+
bower_components
50+
51+
# node-waf configuration
52+
53+
.lock-wscript
54+
55+
# Compiled binary addons (https://nodejs.org/api/addons.html)
56+
57+
build/Release
58+
59+
# Dependency directories
60+
61+
node_modules/
62+
jspm_packages/
63+
64+
# Snowpack dependency directory (https://snowpack.dev/)
65+
66+
web_modules/
67+
68+
# TypeScript cache
69+
70+
*.tsbuildinfo
71+
72+
# Optional npm cache directory
73+
74+
.npm
75+
76+
# Optional eslint cache
77+
78+
.eslintcache
79+
80+
# Optional stylelint cache
81+
82+
.stylelintcache
83+
84+
# Microbundle cache
85+
86+
.rpt2_cache/
87+
.rts2_cache_cjs/
88+
.rts2_cache_es/
89+
.rts2_cache_umd/
90+
91+
# Optional REPL history
92+
93+
.node_repl_history
94+
95+
# Output of 'npm pack'
96+
97+
*.tgz
98+
99+
# Yarn Integrity file
100+
101+
.yarn-integrity
102+
103+
# dotenv environment variable files
104+
105+
.env
106+
.env.development.local
107+
.env.test.local
108+
.env.production.local
109+
.env.local
110+
111+
# parcel-bundler cache (https://parceljs.org/)
112+
113+
.parcel-cache
114+
115+
# Next.js build output
116+
117+
.next
118+
out
119+
120+
# Nuxt.js build / generate output
121+
122+
.nuxt
123+
dist
124+
125+
# Gatsby files
126+
127+
# Comment in the public line in if your project uses Gatsby and not Next.js
128+
129+
# https://nextjs.org/blog/next-9-1#public-directory-support
130+
131+
# public
132+
133+
# vuepress build output
134+
135+
.vuepress/dist
136+
137+
# vuepress v2.x temp and cache directory
138+
139+
.temp
140+
141+
# Docusaurus cache and generated files
142+
143+
.docusaurus
144+
145+
# Serverless directories
146+
147+
.serverless/
148+
149+
# FuseBox cache
150+
151+
.fusebox/
152+
153+
# DynamoDB Local files
154+
155+
.dynamodb/
156+
157+
# TernJS port file
158+
159+
.tern-port
160+
161+
# Stores VSCode versions used for testing VSCode extensions
162+
163+
.vscode-test
164+
165+
# yarn v2
166+
167+
.yarn/cache
168+
.yarn/unplugged
169+
.yarn/build-state.yml
170+
.yarn/install-state.gz
171+
.pnp.*
172+
173+
# IntelliJ based IDEs
174+
.idea
175+
176+
# Finder (MacOS) folder config
177+
.DS_Store
178+
179+
/generated/prisma
180+
bun.lockb
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
# Bun + Prisma ORM + Driver Adapters example
2+
3+
## Introduction
4+
5+
A simple web server using [Bun](https://bun.sh/) and [Prisma ORM](https://www.prisma.io/) with [Prisma Postgres](https://www.prisma.io/postgres). This example helps you build a Bun binary that starts a simple HTTP web server that returns all the users from the database.
6+
7+
This example uses:
8+
9+
- Bun's built-in HTTP server
10+
- New [`prisma-client` generator](https://www.prisma.io/docs/orm/prisma-schema/overview/generators#prisma-client-preview) and the `bun` runtime
11+
- [Driver Adapters (`node-postgres` driver)](https://www.prisma.io/docs/orm/overview/databases/postgresql#using-the-node-postgres-driver)
12+
13+
## Prerequisites
14+
15+
- **Bun**: Make sure you have Bun installed on your system. If not, install it from [bun.sh](https://bun.sh/)
16+
- **Database**: Use a Prisma Postgres database or any other supported database by Prisma. This example uses [Prisma Postgres](https://www.prisma.io/postgres).
17+
18+
## Getting started
19+
20+
### 1. Set up environment variables
21+
22+
Copy the [`.env.example`](./.env.example) file to `.env`:
23+
24+
```bash
25+
cp .env.example .env
26+
```
27+
28+
Run the following command to receive a temporary Prisma Postgres database connection string:
29+
30+
```bash
31+
npx create-db
32+
```
33+
34+
You should have a similar output to the following:
35+
36+
```bash
37+
┌ 🚀 Creating a Prisma Postgres database
38+
39+
│ Provisioning a temporary database in us-east-1...
40+
41+
│ It will be automatically deleted in 24 hours, but you can claim it.
42+
43+
◇ Database created successfully!
44+
45+
46+
● Connect to your database →
47+
48+
│ Use this connection string optimized for Prisma ORM:
49+
50+
$DATABASE_URL
51+
52+
53+
│ Use this connection string for everything else:
54+
55+
$DIRECT_URL
56+
57+
58+
◆ Claim your database →
59+
60+
│ Want to keep your database? Claim for free via this link:
61+
62+
│ https://create-db.prisma.io?projectID=proj_cmf0tcods01d6z1ff9eyvqgd0&utm_source=create-db&utm_medium=cli
63+
64+
│ Your temporary database will be deleted in 24 hours if not claimed.
65+
66+
67+
```
68+
69+
Get the database URL and paste it in your `.env` file:
70+
71+
```bash
72+
DATABASE_URL="your_prisma_postgres_connection_string_here"
73+
DIRECT_URL="your_direct_connection_string_here"
74+
```
75+
76+
- The `DATABASE_URL` is the connection string optimized for Prisma ORM and helps you perform migrations.
77+
- The `DIRECT_URL` is the connection string for everything else and in this case helps you [perform database queries](./db.ts) using driver adapters.
78+
79+
> Learn more about `npx create-db` [in our docs](https://www.prisma.io/docs/postgres/introduction/npx-create-db).
80+
81+
### 2. Install dependencies
82+
83+
```bash
84+
bun install
85+
```
86+
87+
### 3. Run migrations and seed the database
88+
89+
Create a new migration:
90+
91+
```bash
92+
bun prisma migrate dev
93+
```
94+
95+
Generate the Prisma client:
96+
97+
```bash
98+
bun prisma generate
99+
```
100+
101+
Seed the database:
102+
103+
```bash
104+
bun prisma db seed
105+
```
106+
107+
### 4. Start the server
108+
109+
```bash
110+
bun run index.ts
111+
```
112+
113+
Server runs on `http://localhost:3000` and whenever it is visited it returns all the users in the database.
114+
115+
### 5. Build and run a Bun executable
116+
117+
Build the executable:
118+
119+
```bash
120+
bun build --compile index.ts
121+
```
122+
123+
Run the executable:
124+
125+
```bash
126+
./index
127+
```
128+
129+
You should see `Listening on http://localhost:3000` in the console, and when you visit `http://localhost:3000` in your browser, you should see the list of users in the database.
130+
131+
## Project structure
132+
133+
```text
134+
├── prisma/
135+
│ └── schema.prisma # Database schema and Prisma configuration
136+
│ └── seed.ts # Database seed file
137+
├── generated/ # Generated Prisma Client (custom output location)
138+
├── db.ts # Database connection with Prisma driver adapters
139+
├── index.ts # Main server file
140+
├── package.json # Dependencies and scripts
141+
├── prisma.config.ts # Prisma configuration
142+
└── .env.example # Environment variables template
143+
```
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import 'dotenv/config'
2+
import { PrismaClient } from './generated/prisma/client'
3+
import { PrismaPg } from '@prisma/adapter-pg'
4+
5+
const connectionString = `${process.env.DIRECT_URL}`
6+
7+
const adapter = new PrismaPg({ connectionString })
8+
9+
export const prisma = new PrismaClient({ adapter })
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { prisma } from './db'
2+
3+
const server = Bun.serve({
4+
port: 3000,
5+
async fetch(req) {
6+
const { pathname } = new URL(req.url)
7+
8+
// Ignore favicon requests
9+
if (pathname === '/favicon.ico') {
10+
return new Response(null, { status: 204 }) // or serve an icon if you have one
11+
}
12+
13+
// Return all users
14+
const users = await prisma.user.findMany()
15+
16+
// Count all users
17+
const count = await prisma.user.count()
18+
19+
// Format the response with JSON
20+
return new Response(
21+
JSON.stringify({
22+
users: users,
23+
totalUsers: count,
24+
}),
25+
{ headers: { 'Content-Type': 'application/json' } },
26+
)
27+
},
28+
})
29+
30+
console.log(`Listening on http://localhost:${server.port}`)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "bun",
3+
"module": "index.ts",
4+
"type": "module",
5+
"devDependencies": {
6+
"bun-types": "^1.2.21",
7+
"prisma": "^6.15.0"
8+
},
9+
"peerDependencies": {
10+
"typescript": "^5.0.0"
11+
},
12+
"dependencies": {
13+
"@prisma/adapter-pg": "^6.15.0",
14+
"@prisma/client": "^6.15.0",
15+
"add": "^2.0.6",
16+
"bun": "^1.2.21",
17+
"dotenv": "^17.2.1"
18+
}
19+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import 'dotenv/config'
2+
import { defineConfig } from 'prisma/config'
3+
4+
export default defineConfig({
5+
migrations: {
6+
seed: `bun run prisma/seed.ts`,
7+
},
8+
})

0 commit comments

Comments
 (0)