feat: add delete user with specific email helper

This commit is contained in:
Sosokker 2024-11-10 17:34:08 +07:00
parent 5aa99d3951
commit 0bffdf812f
2 changed files with 53 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import { createClient } from "@supabase/supabase-js";
import { getUserUidByEmail } from "./getUser";
const supabase_url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabase_role_key = process.env.SUPABASE_SERVICE_ROLE_KEY;
@ -24,3 +25,18 @@ export async function deleteUser(userId: string) {
throw error;
}
}
export async function deleteUserByEmail(email: string): Promise<boolean> {
const { data: uid, error } = await getUserUidByEmail(email);
if (error) {
console.error(`Error delete user with email: ${email}`, error);
return false;
}
if (!uid) {
console.error(`UID is null`);
return false;
}
const data = await deleteUser(uid);
console.log(`Successfully delete user with email: ${email}`);
return true;
}

37
tests/helpers/getUser.ts Normal file
View File

@ -0,0 +1,37 @@
import { createClient, PostgrestError } from "@supabase/supabase-js";
const supabase_url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabase_role_key = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabase_url) {
throw "Supabase Url is undefine";
}
if (!supabase_role_key) {
throw "Supabase Anon Key is undefine";
}
const supabase = createClient(supabase_url, supabase_role_key);
export async function getUserUidByEmail(email: string): Promise<{ data: string | null; error: PostgrestError | null }> {
try {
const { data, error } = await supabase.rpc("get_user_id_by_email", {
email: email,
});
if (error) {
console.error(`Error retrive user with email: ${email}`, error);
return { data: null, error: error };
}
if (!data) {
console.error(`No user with email: ${email}`, error);
return { data: null, error: error };
}
console.log(`Retrieve UID successfully.`);
return { data: data[0].id, error: error };
} catch (error) {
console.error(`Error retrive user with email: ${email}`, error);
throw error;
}
}