forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayloadClient.ts
More file actions
49 lines (40 loc) · 1.23 KB
/
payloadClient.ts
File metadata and controls
49 lines (40 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { getPayload } from "payload/dist/payload";
import config from "./payload.config";
if (!process.env.MONGODB_URI) {
throw new Error("MONGODB_URI environment variable is missing");
}
if (!process.env.PAYLOAD_SECRET) {
throw new Error("PAYLOAD_SECRET environment variable is missing");
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*
* Source: https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/lib/dbConnect.ts
*/
let cached = (global as any).payload;
if (!cached) {
cached = (global as any).payload = { client: null, promise: null };
}
export const getPayloadClient = async () => {
if (cached.client) {
return cached.client;
}
if (!cached.promise) {
cached.promise = await getPayload({
// Make sure that your environment variables are filled out accordingly
mongoURL: process.env.MONGODB_URI as string,
secret: process.env.PAYLOAD_SECRET as string,
config: config,
});
}
try {
cached.client = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.client;
};
export default getPayloadClient;