Skip to content

Commit c01f0b9

Browse files
committed
Modify disconnected from database per request
1 parent a0cc2e4 commit c01f0b9

11 files changed

+64
-38
lines changed

Dockerfile

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FROM node:18.16-bullseye-slim as base
2+
3+
RUN apt-get update && apt-get install -y clang libc++-dev libc++abi-dev build-essential
4+
5+
WORKDIR /app

README.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ A program to set up a GraphQL server on Cloudflare Workers.
1414

1515
```sh
1616
$ docker compose up
17-
$ npm install
18-
$ npm run migrate:dev
19-
$ npm run start
2017
#=> http://localhost:8787/graphql
18+
19+
# If you want it to work in your local environment
20+
# npm install
21+
# npm run prisma migrate deploy
22+
# npm run start
2123
```
2224

2325
## License

compose.yml

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,19 @@
11
services:
2+
app:
3+
build:
4+
context: .
5+
target: base
6+
entrypoint: ./scripts/docker-entrypoint.sh
7+
command: npm run start
8+
volumes:
9+
- .:/app
10+
depends_on:
11+
- db
12+
ports:
13+
- 8787:8787
14+
environment:
15+
- DATABASE_URL=postgres://postgres:password@db:5432/postgres
216
db:
317
image: postgres:15.1-alpine3.17
4-
ports:
5-
- 5432:5432
618
environment:
719
- POSTGRES_PASSWORD=password

package-lock.json

+4-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"private": true,
55
"scripts": {
66
"deploy": "wrangler publish",
7-
"migrate:dev": "DATABASE_URL=postgres://postgres:password@localhost:5432/postgres prisma migrate dev",
7+
"migrate:dev": "prisma migrate dev",
88
"start": "wrangler dev"
99
},
1010
"devDependencies": {
@@ -13,7 +13,7 @@
1313
"prisma": "^4.14.1",
1414
"prisma-kysely": "^1.4.1",
1515
"typescript": "^5.0.4",
16-
"wrangler": "^3.0.0"
16+
"wrangler": "^3.1.0"
1717
},
1818
"dependencies": {
1919
"@pothos/core": "^3.30.0",

scripts/docker-entrypoint.sh

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#!/bin/sh
2+
3+
npm ci
4+
npm run prisma migrate deploy
5+
6+
exec "$@"

src/builder.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { Context } from './context'
12
import SchemaBuilder from '@pothos/core'
23

3-
export const builder = new SchemaBuilder({})
4+
export const builder = new SchemaBuilder<{Context: Context}>({})

src/context.ts

+13-6
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,21 @@ import { Kysely, PostgresDialect } from 'kysely'
55
// MEMO: https://developers.cloudflare.com/workers/databases/connect-to-postgres/#connection-pooling--startup
66
// Cloudflare Workers seems to require a TCP connection for each connection. Therefore, using Kysely's Connection Pooling will not work properly as it will not connect when a second request is received.
77
// Therefore, I try to make the connection each time.
8-
export const connection = () => new Kysely<DB>({
8+
const connection = (connectionString: string) => new Kysely<DB>({
99
// Use MysqlDialect for MySQL and SqliteDialect for SQLite.
1010
dialect: new PostgresDialect({
1111
pool: new Pool({
12-
host: 'localhost',
13-
database: 'postgres',
14-
user: 'postgres',
15-
password: 'password',
12+
connectionString
1613
}),
1714
}),
18-
})
15+
})
16+
17+
export type Context = {
18+
db: Kysely<DB>
19+
}
20+
21+
export const createContext = (connectionString: string): Context => {
22+
return {
23+
db: connection(connectionString)
24+
}
25+
}

src/resolvers/User/query.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import { builder } from '../../builder'
22
import { UserType } from '../../models/User'
3-
import { connection } from '../../context'
43

54
builder.queryFields((t) => ({
65
User: t.field({
76
type: UserType,
87
nullable: true,
9-
resolve: async () => {
10-
const db = connection()
11-
return await db.selectFrom('User').selectAll().executeTakeFirst()
8+
resolve: async (_root, _args, ctx) => {
9+
return await ctx.db.selectFrom('User').selectAll().executeTakeFirst()
1210
},
1311
}),
1412
}))

src/worker.ts

+8-16
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,22 @@
99
*/
1010

1111
export interface Env {
12-
// Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
13-
// MY_KV_NAMESPACE: KVNamespace;
14-
//
15-
// Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
16-
// MY_DURABLE_OBJECT: DurableObjectNamespace;
17-
//
18-
// Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
19-
// MY_BUCKET: R2Bucket;
20-
//
21-
// Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/
22-
// MY_SERVICE: Fetcher;
23-
//
24-
// Example binding to a Queue. Learn more at https://developers.cloudflare.com/queues/javascript-apis/
25-
// MY_QUEUE: Queue;
12+
DATABASE_URL: string
2613
}
2714

2815
import { createYoga } from 'graphql-yoga'
2916
import { schema } from './schema'
17+
import { createContext } from './context'
3018

3119
// Create a Yoga instance with a GraphQL schema.
3220
const yoga = createYoga({ schema })
3321

3422
export default {
3523
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
36-
return yoga(request, env, ctx)
24+
const context = createContext(env.DATABASE_URL)
25+
const response = await yoga(request, context)
26+
27+
await context.db.destroy()
28+
return response
3729
},
38-
}
30+
}

wrangler.toml

+3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ compatibility_date = "2023-05-25"
44

55
node_compat = true
66

7+
[vars]
8+
DATABASE_URL='postgres://postgres:password@db:5432/postgres'
9+
710
# # KV Namespace binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/kv
811
# [[kv_namespaces]]
912
# binding = "MY_KV_NAMESPACE"

0 commit comments

Comments
 (0)