@@ -10,19 +10,41 @@ import { genSaltSync, hashSync } from 'bcrypt-ts';
10
10
let client = postgres ( `${ process . env . POSTGRES_URL ! } ?sslmode=require` ) ;
11
11
let db = drizzle ( client ) ;
12
12
13
- let users = pgTable ( 'User' , {
14
- id : serial ( 'id' ) . primaryKey ( ) ,
15
- email : varchar ( 'email' , { length : 64 } ) ,
16
- password : varchar ( 'password' , { length : 64 } ) ,
17
- } ) ;
18
-
19
13
export async function getUser ( email : string ) {
14
+ const users = await ensureTableExists ( ) ;
20
15
return await db . select ( ) . from ( users ) . where ( eq ( users . email , email ) ) ;
21
16
}
22
17
23
18
export async function createUser ( email : string , password : string ) {
19
+ const users = await ensureTableExists ( ) ;
24
20
let salt = genSaltSync ( 10 ) ;
25
21
let hash = hashSync ( password , salt ) ;
26
22
27
23
return await db . insert ( users ) . values ( { email, password : hash } ) ;
28
24
}
25
+
26
+ async function ensureTableExists ( ) {
27
+ const result = await client `
28
+ SELECT EXISTS (
29
+ SELECT FROM information_schema.tables
30
+ WHERE table_schema = 'public'
31
+ AND table_name = 'User'
32
+ );` ;
33
+
34
+ if ( ! result [ 0 ] . exists ) {
35
+ await client `
36
+ CREATE TABLE "User" (
37
+ id SERIAL PRIMARY KEY,
38
+ email VARCHAR(64),
39
+ password VARCHAR(64)
40
+ );` ;
41
+ }
42
+
43
+ const table = pgTable ( 'User' , {
44
+ id : serial ( 'id' ) . primaryKey ( ) ,
45
+ email : varchar ( 'email' , { length : 64 } ) ,
46
+ password : varchar ( 'password' , { length : 64 } ) ,
47
+ } ) ;
48
+
49
+ return table ;
50
+ }
0 commit comments