Files
flyer-crawler.projectium.com/supabase/functions/seed-database/index.ts

113 lines
3.7 KiB
TypeScript

// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.
// Setup type definitions for built-in Supabase Runtime APIs
//import "jsr:@supabase/functions-js/edge-runtime.d.ts"
//console.log("Hello from Functions!")
//Deno.serve(async (req) => {
// const { name } = await req.json()
// const data = {
// message: `Hello ${name}!`,
// }
//
// return new Response(
// JSON.stringify(data),
// { headers: { "Content-Type": "application/json" } },
// )
//})
/* To invoke locally:
1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
2. Make an HTTP request:
curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/seed-database' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \
--header 'Content-Type: application/json' \
--data '{"name":"Functions"}'
*/
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { corsHeaders } from '../_shared/.temp/functions/_shared/cors.ts';
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response('ok', { headers: corsHeaders });
}
try {
// We create an admin client using the service_role key to perform elevated actions.
// This key is automatically provided by Supabase in the production environment.
const adminSupabaseClient = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
{ auth: { autoRefreshToken: false, persistSession: false } }
);
const usersToSeed = [
{
email: 'admin@example.com',
password: 'password123',
user_metadata: { full_name: 'Admin User' }
},
{
email: 'user@example.com',
password: 'password123',
user_metadata: { full_name: 'Normal User' }
}
];
const createdUsers = [];
const existingUsers = [];
const { data: { users: existingUserList }, error: listError } = await adminSupabaseClient.auth.admin.listUsers();
if (listError) throw listError;
const existingEmails = new Set(existingUserList.map(u => u.email));
for (const user of usersToSeed) {
if (!existingEmails.has(user.email)) {
const { error } = await adminSupabaseClient.auth.admin.createUser({
email: user.email,
password: user.password,
user_metadata: user.user_metadata,
email_confirm: true, // Auto-confirm for dev environment
});
if (error) {
throw new Error(`Failed to create user ${user.email}: ${error.message}`);
}
createdUsers.push(user.email);
} else {
existingUsers.push(user.email);
}
}
let message = '';
if (createdUsers.length > 0) {
message += `Successfully created users: ${createdUsers.join(', ')}. `;
}
if (existingUsers.length > 0) {
message += `Users already existed: ${existingUsers.join(', ')}.`;
}
if (message === '') {
message = 'All development users already exist.'
}
return new Response(JSON.stringify({ message: message.trim() }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
});
} catch (error) {
// Return a detailed error with a stack trace for better debugging.
return new Response(JSON.stringify({ error: error.message, stack: error.stack }), {
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
});
}
});