93 lines
2.8 KiB
TypeScript
93 lines
2.8 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { createClient, SupabaseAuthUser, SupabaseClient } from '@supabase/supabase-js'
|
|
import { Subject } from 'rxjs';
|
|
import { environment } from '../../../environments/environment'
|
|
import { User } from './user';
|
|
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class SupaService {
|
|
client: SupabaseClient;
|
|
user: Subject<SupabaseAuthUser> = new Subject();
|
|
supabaseUser: SupabaseAuthUser;
|
|
userProfile: User;
|
|
|
|
constructor() {
|
|
// Create a single supabase client for interacting with your database
|
|
this.client = createClient(environment.supa_url, environment.supa_key);
|
|
this.getUser();
|
|
}
|
|
|
|
async getUser() {
|
|
const user = await this.client.auth.user();
|
|
console.log('user', user);
|
|
this.supabaseUser = user;
|
|
this.getUserProfile();
|
|
this.user.next(user);
|
|
}
|
|
|
|
getUserProfile(user_id: string = this.supabaseUser.id) {
|
|
const subject: Subject<User> = new Subject();
|
|
if (!this.userProfile) {
|
|
this.client.from<User>('user').select().match({id: <never>user_id})
|
|
.then(data => {
|
|
console.log('getUserProfile', data)
|
|
if (data.body.length === 0) {
|
|
// create default user profile
|
|
this.client.from<User>('user').insert(new User(user_id, this.supabaseUser.email.split('@')[0]))
|
|
.then(data => {
|
|
console.log('created UserProfile', data.body[0]);
|
|
this.userProfile = data.body[0];
|
|
subject.next(this.userProfile);
|
|
})
|
|
.catch(error => console.error('Error creating UserProfile', error))
|
|
} else {
|
|
console.log('loaded UserProfile', data.body[0]);
|
|
this.userProfile = data.body[0];
|
|
subject.next(this.userProfile);
|
|
}
|
|
})
|
|
.catch(error => console.error('getUserProfile', error))
|
|
} else {
|
|
setTimeout(() =>subject.next(this.userProfile), 100);
|
|
}
|
|
return subject.asObservable();
|
|
}
|
|
|
|
async login(email: string, password: string): Promise<SupabaseAuthUser> {
|
|
try {
|
|
const res = await this.client.auth.login(
|
|
email,
|
|
password
|
|
);
|
|
this.user.next(res.body.user);
|
|
this.supabaseUser = res.body.user;
|
|
return res.body.user;
|
|
} catch (e) {
|
|
console.error('Login', e);
|
|
}
|
|
}
|
|
|
|
async logout(): Promise<any> {
|
|
return this.client.auth.logout()
|
|
.then(() => this.user.next(null))
|
|
.catch((e) =>console.error('Logout', e));
|
|
}
|
|
|
|
async signup(email: string, password: string): Promise<SupabaseAuthUser> {
|
|
try {
|
|
const res = await this.client.auth.signup(
|
|
email,
|
|
password
|
|
);
|
|
this.user.next(res.body.user);
|
|
this.supabaseUser = res.body.user;
|
|
return res.body.user;
|
|
} catch (e) {
|
|
console.error('Signup', e);
|
|
}
|
|
}
|
|
|
|
}
|