249 lines
9.1 KiB
TypeScript
249 lines
9.1 KiB
TypeScript
// import { createClient } from '@supabase/supabase-js';
|
|
import type {AdminUserAttributes, Session, UserResponse} from '@supabase/supabase-js';
|
|
// import {type AuthTokenResponsePassword, createClient} from '@supabase/supabase-js';
|
|
import type {Token, User, UserLoginState} from "@/models/login";
|
|
import {message} from "ant-design-vue";
|
|
// import type {User} from "@/model/User";
|
|
|
|
const SUPABASE_URL = 'https://supa.machartaa.ir';
|
|
const SUPABASE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlhdCI6MTcxMDAwMDAwMCwiZXhwIjoxOTkwMDAwMDAwfQ.C-w5Uc3jnaXmxb2YBoivAdB3RCTt03FioW6wWyYjmb4';
|
|
|
|
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
|
|
|
// --- Lazy runtime init (بدون تغییر API) ---
|
|
let _client: SupabaseClient | null = null
|
|
export const supabase = createClient(SUPABASE_URL,SUPABASE_KEY);
|
|
|
|
// function ensureClient(): SupabaseClient {
|
|
// if (_client) return _client
|
|
// const cfg = useRuntimeConfig().public as {
|
|
// SUPABASE_URL: string
|
|
// SUPABASE_KEY: string
|
|
// }
|
|
// if (!cfg?.SUPABASE_URL || !cfg?.SUPABASE_KEY) {
|
|
// console.warn('[supabase] Missing SUPABASE_URL/KEY in runtimeConfig.public')
|
|
// }
|
|
// _client = createClient(cfg.SUPABASE_URL, cfg.SUPABASE_KEY)
|
|
// return _client
|
|
// }
|
|
|
|
// ✅ همان export قبلی، اما بهصورت Proxy که هنگام اولین استفاده، کلاینت را با runtimeConfig میسازد
|
|
// export const supabase = new Proxy({} as SupabaseClient, {
|
|
// get(_t, prop, receiver) {
|
|
// const c = ensureClient()
|
|
// // @ts-ignore
|
|
// return Reflect.get(c, prop, receiver)
|
|
// },
|
|
// apply(_t, thisArg, argArray) {
|
|
// // احتیاط برای مواقعی که بهصورت تابعی صدا زده شود
|
|
// // @ts-ignore
|
|
// return (ensureClient() as any)?.apply?.(thisArg, argArray)
|
|
// },
|
|
// })
|
|
|
|
// ✅ بدون نیاز به ثابت build-time؛ هر بار از runtimeConfig میسازد
|
|
export const getSupabaseStorageUrl = (path: string) => {
|
|
const cfg = useRuntimeConfig().public as { SUPABASE_BASE_IMAGE_URL: string }
|
|
return `${cfg.SUPABASE_BASE_IMAGE_URL}/${path}`
|
|
}
|
|
|
|
export const uploadFile = async (file: FileList, busket: string = 'productimg') => {
|
|
const uniqueFileName = `${Date.now()}-${file.name}`;
|
|
return await supabase
|
|
.storage
|
|
.from(busket)
|
|
.upload(uniqueFileName, file, {
|
|
cacheControl: '3600',
|
|
upsert: false
|
|
})
|
|
}
|
|
|
|
interface Query {
|
|
columns?: string,
|
|
field?: string | string[],
|
|
value?: string | string[] | number | number[]
|
|
data?: any
|
|
}
|
|
|
|
export const supabaseService = {
|
|
// Generic fetch method for CRUD operations
|
|
async fetch<T>(
|
|
table: string,
|
|
method: 'select' | 'insert' | 'update' | 'delete' | 'select_group',
|
|
query: Query = {},
|
|
customErrorMessage?: string,
|
|
order?:{column:string,ascending:boolean}
|
|
): Promise<T | null> {
|
|
try {
|
|
let result;
|
|
switch (method) {
|
|
case 'select': {
|
|
let queryBuilder = supabase.from(table);
|
|
let selectQuery = queryBuilder.select(query.columns || '*');
|
|
|
|
// Apply multiple .eq() conditions dynamically
|
|
if (query.field && query.value) {
|
|
if (Array.isArray(query.field) && Array.isArray(query.value)) {
|
|
query.field.forEach((f, i) => {
|
|
selectQuery = selectQuery.eq(f, query.value[i]);
|
|
});
|
|
} else {
|
|
// console.log('salam', query.field, query.value)
|
|
selectQuery = selectQuery.eq(query.field, query.value);
|
|
}
|
|
}
|
|
if (order?.column){
|
|
selectQuery = selectQuery.order(order.column,{ascending:order.ascending})
|
|
}
|
|
// console.log('salam', selectQuery)
|
|
result = await selectQuery;
|
|
break;
|
|
}
|
|
case 'select_group':
|
|
result = await supabase.from(table).select(query.columns|| '*').in(query.field ?? '', query.value)
|
|
break;
|
|
case 'insert':
|
|
result = await supabase.from(table).insert(query.data).select('*')
|
|
break;
|
|
case 'update':
|
|
result = await supabase.from(table).update(query.data).eq(query.field ?? '', query.value).select();
|
|
break;
|
|
case 'delete': {
|
|
let deleteQuery = supabase.from(table).delete();
|
|
if (Array.isArray(query.field) && Array.isArray(query.value)) {
|
|
query.field.forEach((f, i) => {
|
|
deleteQuery = deleteQuery.eq(f, query.value[i]);
|
|
});
|
|
} else {
|
|
deleteQuery = deleteQuery.eq(query.field ?? '', query.value);
|
|
}
|
|
result = await deleteQuery;
|
|
break;
|
|
}
|
|
|
|
default:
|
|
throw new Error('Unsupported method');
|
|
}
|
|
|
|
if (result.error) {
|
|
// errorMessage(result.error.message)
|
|
throw result.error
|
|
} else {
|
|
return result.data
|
|
}
|
|
} catch (err) {
|
|
console.error(customErrorMessage || 'Unexpected Supabase Error:', err);
|
|
errorMessage(err.message as string)
|
|
throw err;
|
|
}
|
|
},
|
|
// async updateUserDetails(
|
|
// email,
|
|
// phone,
|
|
// password
|
|
// ): Promise<User> {
|
|
// try {
|
|
// const res = await supabase.auth.updateUser({
|
|
// email,
|
|
// phone,
|
|
// password
|
|
// });
|
|
//
|
|
// /* if (error) {
|
|
// console.error('Error updating user:', error);
|
|
// errorMessage(error.message as string)
|
|
// throw error;
|
|
// }*/
|
|
// if (res.error) {
|
|
// throw res.error
|
|
// } else {
|
|
// return res.data.user
|
|
// }
|
|
// } catch (err) {
|
|
// console.error('Unexpected error while updating user:', err);
|
|
// errorMessage(err.message as string)
|
|
// throw err;
|
|
// }
|
|
// },
|
|
// async createUser(params: User): Promise<UserResponse> {
|
|
// try {
|
|
// return (await supabase.auth.admin.createUser(params))
|
|
// } catch (err) {
|
|
// console.error('Unexpected Error:', err);
|
|
// errorMessage(err as string)
|
|
// throw err
|
|
// }
|
|
// },
|
|
// // Authentication methods
|
|
// async login(params: UserLoginState): Promise<Token> {
|
|
// try {
|
|
// const res = await supabase.auth.signInWithPassword(params)
|
|
// if (res.error) {
|
|
// throw res.error
|
|
// } else {
|
|
// return res.data.user
|
|
// }
|
|
// } catch (err) {
|
|
// console.error('Unexpected Login Error:', err);
|
|
// errorMessage(err.message as string)
|
|
// throw err
|
|
// }
|
|
// },
|
|
//
|
|
// async deleteUser(user_id: string): Promise<UserResponse> {
|
|
// try {
|
|
// return (await supabase.auth.admin.deleteUser(<string>user_id))
|
|
// } catch (err) {
|
|
// console.error('Unexpected Login Error:', err);
|
|
// errorMessage(err as string)
|
|
// throw err
|
|
// }
|
|
// },
|
|
// async signup(email: string, password: string): Promise<{ user: any; session: Session | null } | null> {
|
|
// try {
|
|
// const {user, session, error} = await supabase.auth.signUp({
|
|
// email,
|
|
// password,
|
|
// });
|
|
//
|
|
// if (error) {
|
|
// console.error('Signup Error:', error.message);
|
|
// errorMessage(error.message)
|
|
// return null;
|
|
// }
|
|
//
|
|
// return {user, session};
|
|
// } catch (err) {
|
|
// console.error('Unexpected Signup Error:', err);
|
|
// return null;
|
|
// }
|
|
// },
|
|
//
|
|
// async logout(): Promise<boolean> {
|
|
// try {
|
|
// const {error} = await supabase.auth.signOut();
|
|
//
|
|
// if (error) {
|
|
// console.error('Logout Error:', error.message);
|
|
// return false;
|
|
// }
|
|
//
|
|
// return true;
|
|
// } catch (err) {
|
|
// console.error('Unexpected Logout Error:', err);
|
|
// return false;
|
|
// }
|
|
// },
|
|
//
|
|
// getUser(): any | null {
|
|
// return supabase.auth.getUser();
|
|
// },
|
|
//
|
|
// onAuthStateChange(callback: (event: string, session: Session | null) => void) {
|
|
// supabase.auth.onAuthStateChange(callback);
|
|
// },
|
|
};
|
|
|
|
function errorMessage(msg: string) {
|
|
message.error(msg).then(r => '');
|
|
} |