Skip to content

Commit 508a93f

Browse files
committed
workerで動くよう修正
1 parent 4e1c055 commit 508a93f

File tree

8 files changed

+67
-60
lines changed

8 files changed

+67
-60
lines changed

.gitignore

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,3 @@ yarn-error.log*
4242
# typescript
4343
*.tsbuildinfo
4444
next-env.d.ts
45-
46-
/app/generated/prisma

app/api/auth/[...all]/route.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { auth } from "@/lib/auth"; // path to your auth file
1+
import { getAuthServer } from "@/lib/auth";
2+
import { getPrismaClient } from "@/lib/prisma";
23
import { toNextJsHandler } from "better-auth/next-js";
34

4-
export const { POST, GET } = toNextJsHandler(auth);
5+
export const { POST, GET } = toNextJsHandler({
6+
handler: async (req) =>
7+
(await getAuthServer(await getPrismaClient())).handler(req),
8+
});

app/lib/auth.ts

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,43 @@ import { betterAuth } from "better-auth";
22
import { prismaAdapter } from "better-auth/adapters/prisma";
33
import { getCloudflareContext } from "@opennextjs/cloudflare";
44
import { anonymous } from "better-auth/plugins";
5-
import prisma from "./prisma";
65
import { migrateChatUser } from "./chatHistory";
6+
import { PrismaClient } from "@prisma/client";
77

8-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
9-
let cloudflareEnv: any;
10-
try {
11-
cloudflareEnv = getCloudflareContext().env;
12-
} catch {
13-
// @better-auth/cli generate を実行する際には initOpenNextCloudflareForDev がセットアップされていない環境になっている
14-
cloudflareEnv = {};
15-
}
16-
export const auth = betterAuth({
17-
database: prismaAdapter(prisma, {
18-
provider: "postgresql",
19-
}),
20-
plugins: [
21-
anonymous({
22-
onLinkAccount: ({ anonymousUser, newUser }) =>
23-
migrateChatUser(anonymousUser.user.id, newUser.user.id),
8+
export async function getAuthServer(prisma: PrismaClient) {
9+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
10+
let cloudflareEnv: any;
11+
try {
12+
cloudflareEnv = getCloudflareContext().env;
13+
} catch {
14+
// @better-auth/cli generate を実行する際には initOpenNextCloudflareForDev がセットアップされていない環境になっている
15+
cloudflareEnv = {};
16+
}
17+
return betterAuth({
18+
database: prismaAdapter(prisma, {
19+
provider: "sqlite",
2420
}),
25-
],
26-
socialProviders: {
27-
github: {
28-
clientId: process.env.GITHUB_CLIENT_ID ?? cloudflareEnv.GITHUB_CLIENT_ID,
29-
clientSecret:
30-
process.env.GITHUB_CLIENT_SECRET ?? cloudflareEnv.GITHUB_CLIENT_SECRET,
31-
},
32-
google: {
33-
clientId: process.env.GOOGLE_CLIENT_ID ?? cloudflareEnv.GOOGLE_CLIENT_ID,
34-
clientSecret:
35-
process.env.GOOGLE_CLIENT_SECRET ?? cloudflareEnv.GOOGLE_CLIENT_SECRET,
21+
plugins: [
22+
anonymous({
23+
onLinkAccount: ({ anonymousUser, newUser }) =>
24+
migrateChatUser(anonymousUser.user.id, newUser.user.id),
25+
}),
26+
],
27+
socialProviders: {
28+
github: {
29+
clientId:
30+
process.env.GITHUB_CLIENT_ID ?? cloudflareEnv.GITHUB_CLIENT_ID,
31+
clientSecret:
32+
process.env.GITHUB_CLIENT_SECRET ??
33+
cloudflareEnv.GITHUB_CLIENT_SECRET,
34+
},
35+
google: {
36+
clientId:
37+
process.env.GOOGLE_CLIENT_ID ?? cloudflareEnv.GOOGLE_CLIENT_ID,
38+
clientSecret:
39+
process.env.GOOGLE_CLIENT_SECRET ??
40+
cloudflareEnv.GOOGLE_CLIENT_SECRET,
41+
},
3642
},
37-
},
38-
});
43+
});
44+
}

app/lib/chatHistory.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { headers } from "next/headers";
2-
import { auth } from "./auth";
3-
import prisma from "./prisma";
2+
import { getAuthServer } from "./auth";
3+
import { getPrismaClient } from "./prisma";
44

55
export interface CreateChatMessage {
66
role: "user" | "ai" | "error";
@@ -12,6 +12,8 @@ export async function addChat(
1212
sectionId: string,
1313
messages: CreateChatMessage[]
1414
) {
15+
const prisma = await getPrismaClient();
16+
const auth = await getAuthServer(prisma);
1517
const session = await auth.api.getSession({ headers: await headers() });
1618
if (!session) {
1719
throw new Error("Not authenticated");
@@ -37,6 +39,8 @@ export async function addChat(
3739
export type ChatWithMessages = Awaited<ReturnType<typeof addChat>>;
3840

3941
export async function getChat(docsId: string) {
42+
const prisma = await getPrismaClient();
43+
const auth = await getAuthServer(prisma);
4044
const session = await auth.api.getSession({ headers: await headers() });
4145
if (!session) {
4246
return [];
@@ -61,6 +65,7 @@ export async function getChat(docsId: string) {
6165
}
6266

6367
export async function migrateChatUser(oldUserId: string, newUserId: string) {
68+
const prisma = await getPrismaClient();
6469
await prisma.chat.updateMany({
6570
where: {
6671
userId: oldUserId,

app/lib/prisma.ts

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,16 @@
1-
import { PrismaClient } from "../generated/prisma/client";
2-
import { PrismaPg } from "@prisma/adapter-pg";
3-
import { PrismaNeon } from "@prisma/adapter-neon";
41
import { getCloudflareContext } from "@opennextjs/cloudflare";
2+
import { PrismaClient } from "@prisma/client";
3+
import { PrismaD1 } from "@prisma/adapter-d1";
54

6-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
7-
let cloudflareEnv: any;
8-
try {
9-
cloudflareEnv = getCloudflareContext().env;
10-
} catch {
11-
// @better-auth/cli generate を実行する際には initOpenNextCloudflareForDev がセットアップされていない環境になっている
12-
cloudflareEnv = {};
13-
}
14-
const DATABASE_URL =
15-
process.env.DATABASE_URL ?? cloudflareEnv.DATABASE_URL ?? "";
5+
export async function getPrismaClient() {
6+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
7+
let cloudflareEnv: any;
8+
try {
9+
cloudflareEnv = (await getCloudflareContext({ async: true })).env;
10+
} catch {
11+
// @better-auth/cli generate を実行する際には initOpenNextCloudflareForDev がセットアップされていない環境になっている
12+
cloudflareEnv = {};
13+
}
1614

17-
let adapter;
18-
if (DATABASE_URL.includes("neon")) {
19-
adapter = new PrismaNeon({ connectionString: DATABASE_URL });
20-
} else {
21-
adapter = new PrismaPg({ connectionString: DATABASE_URL });
15+
return new PrismaClient({ adapter: new PrismaD1(cloudflareEnv.my_code_db) });
2216
}
23-
const prisma = new PrismaClient({ adapter });
24-
export default prisma;

next.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const nextConfig: NextConfig = {
1515
env: {
1616
PYODIDE_VERSION: pyodideVersion,
1717
},
18+
serverExternalPackages: ["@prisma/client", ".prisma/client"],
1819
};
1920

2021
export default nextConfig;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"lint": "prisma generate && npm run cf-typegen && next lint",
1010
"tsc": "prisma generate && npm run cf-typegen && tsc",
1111
"format": "prettier --write app/",
12-
"cf-preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
12+
"cf-preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview --port 3000",
1313
"cf-deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy",
1414
"cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
1515
},

prisma/schema.prisma

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
66

77
generator client {
8-
provider = "prisma-client"
9-
output = "../app/generated/prisma"
10-
engineType = "client"
8+
provider = "prisma-client-js"
9+
// outputを指定すると動作しない: https://opennext.js.org/cloudflare/howtos/db#schemaprisma
10+
// output = "../app/generated/prisma"
11+
// engineType = "client"
1112
}
1213

1314
datasource db {

0 commit comments

Comments
 (0)