-
Notifications
You must be signed in to change notification settings - Fork 1
/
connect.ts
53 lines (45 loc) · 1.56 KB
/
connect.ts
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
50
51
52
53
import 'server-only';
import { unstable_noStore as noStore } from 'next/cache';
import postgres, { Sql } from 'postgres';
import postgresConfig from '../ley.config';
import { setEnvironmentVariables } from '../util/config';
setEnvironmentVariables();
declare module globalThis {
let postgresSqlClient: Sql;
}
// Connect only once to the database
// https://github.com/vercel/next.js/issues/7811#issuecomment-715259370
function connectOneTimeToDatabase() {
if (!('postgresSqlClient' in globalThis)) {
globalThis.postgresSqlClient = postgres(postgresConfig);
}
// Workaround to force Next.js Dynamic Rendering on every database query:
//
// Wrap sql`` tagged template function to call `noStore()` from
// next/cache before each database query. `noStore()` is a
// Next.js Dynamic Function, which causes the page to use
// Dynamic Rendering
//
// https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering
//
// Ideally there would something built into Next.js for this,
// which has been requested here:
//
// https://github.com/vercel/next.js/discussions/50695
return ((
...sqlParameters: Parameters<typeof globalThis.postgresSqlClient>
) => {
noStore();
return globalThis.postgresSqlClient(...sqlParameters);
}) as typeof globalThis.postgresSqlClient;
}
export const sql = connectOneTimeToDatabase();
// import { config } from 'dotenv-safe';
// import postgres from 'postgres';
// config();
// export const sql = postgres({
// transform: {
// ...postgres.camel,
// undefined: null,
// },
// });