Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5eb8c5e

Browse files
Migrate 'nextjs-with-mongodb' example to TypeScript
1 parent 0ce8c0e commit 5eb8c5e

File tree

12 files changed

+3201
-732
lines changed

12 files changed

+3201
-732
lines changed

‎.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
/node_modules
55
/.pnp
66
.pnp.js
7+
.yarn/install-state.gz
78

89
# testing
910
/coverage
@@ -23,7 +24,6 @@
2324
npm-debug.log*
2425
yarn-debug.log*
2526
yarn-error.log*
26-
.pnpm-debug.log*
2727

2828
# local env files
2929
.env*.local
@@ -33,4 +33,4 @@ yarn-error.log*
3333

3434
# typescript
3535
*.tsbuildinfo
36-
next-env.d.ts
36+
next-env.d.ts

‎lib/mongodb.js

Lines changed: 0 additions & 29 deletions
This file was deleted.

‎lib/mongodb.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { MongoClient } from "mongodb";
2+
3+
if (!process.env.MONGODB_URI) {
4+
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
5+
}
6+
7+
const uri = process.env.MONGODB_URI;
8+
const options = {};
9+
10+
let client;
11+
let clientPromise: Promise<MongoClient>;
12+
13+
if (process.env.NODE_ENV === "development") {
14+
// In development mode, use a global variable so that the value
15+
// is preserved across module reloads caused by HMR (Hot Module Replacement).
16+
let globalWithMongo = global as typeof globalThis & {
17+
_mongoClientPromise?: Promise<MongoClient>;
18+
};
19+
20+
if (!globalWithMongo._mongoClientPromise) {
21+
client = new MongoClient(uri, options);
22+
globalWithMongo._mongoClientPromise = client.connect();
23+
}
24+
clientPromise = globalWithMongo._mongoClientPromise;
25+
} else {
26+
// In production mode, it's best to not use a global variable.
27+
client = new MongoClient(uri, options);
28+
clientPromise = client.connect();
29+
}
30+
31+
// Export a module-scoped MongoClient promise. By doing this in a
32+
// separate module, the client can be shared across functions.
33+
export default clientPromise;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /