-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
seed.server.ts
95 lines (77 loc) · 1.82 KB
/
seed.server.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* eslint-disable no-console */
import { PrismaClient } from "@prisma/client";
import { createClient } from "@supabase/supabase-js";
import { SUPABASE_SERVICE_ROLE, SUPABASE_URL } from "../utils/env";
const supabaseAdmin = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE, {
auth: {
autoRefreshToken: false,
persistSession: false,
},
});
const prisma = new PrismaClient();
const email = "[email protected]";
const getUserId = async (): Promise<string> => {
const userList = await supabaseAdmin.auth.admin.listUsers();
if (userList.error) {
throw userList.error;
}
const existingUserId = userList.data.users.find(
(user) => user.email === email,
)?.id;
if (existingUserId) {
return existingUserId;
}
const newUser = await supabaseAdmin.auth.admin.createUser({
email,
password: "supabase",
email_confirm: true,
});
if (newUser.error) {
throw newUser.error;
}
return newUser.data.user.id;
};
async function seed() {
try {
const id = await getUserId();
// cleanup the existing database
await prisma.user.delete({ where: { email } }).catch(() => {
// no worries if it doesn't exist yet
});
const user = await prisma.user.create({
data: {
email,
id,
},
});
await prisma.note.create({
data: {
title: "My first note",
body: "Hello, world!",
userId: user.id,
},
});
await prisma.note.create({
data: {
title: "My second note",
body: "Hello, world!",
userId: user.id,
},
});
console.log(`Database has been seeded. 🌱\n`);
console.log(
`User added to your database 👇 \n🆔: ${user.id}\n📧: ${user.email}\n🔑: supabase`,
);
} catch (cause) {
console.error(cause);
throw new Error("Seed failed 🥲");
}
}
seed()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});