@e-techsolutions/e-baas-sdk
Version:
Official E-BaaS TypeScript SDK - Backend as a Service client library
623 lines (603 loc) • 18.6 kB
TypeScript
import { HttpClient as HttpClient$1, EBaaSError as EBaaSError$1 } from 'infra';
import { SelectOptions as SelectOptions$1, InsertOptions as InsertOptions$1, UpdateOptions as UpdateOptions$1, DeleteOptions as DeleteOptions$1 } from 'infra/types/common';
import { Socket } from 'socket.io-client';
import { EventEmitter } from 'eventemitter3';
import { AxiosRequestConfig } from 'axios';
interface HttpClientConfig {
url: string;
apiKey: string;
timeout?: number;
headers?: Record<string, string>;
}
interface ApiResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
}
declare class HttpClient {
private client;
private baseURL;
private apiKey;
constructor(config: HttpClientConfig);
private setupInterceptors;
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
setAuthToken(token: string): void;
removeAuthToken(): void;
private handleError;
}
declare class EBaaSError extends Error {
readonly status: number;
readonly details?: any;
constructor(message: string, status?: number, details?: any);
toJSON(): {
name: string;
message: string;
status: number;
details: any;
stack: string | undefined;
};
toString(): string;
}
interface EBaaSClientOptions {
supabaseUrl: string;
supabaseKey: string;
options?: {
auth?: {
autoRefreshToken?: boolean;
persistSession?: boolean;
detectSessionInUrl?: boolean;
};
realtime?: {
params?: Record<string, string>;
};
global?: {
headers?: Record<string, string>;
};
};
}
interface DatabaseFilters {
eq?: any;
neq?: any;
gt?: any;
gte?: any;
lt?: any;
lte?: any;
like?: string;
ilike?: string;
is?: any;
in?: any[];
contains?: any;
contained_by?: any;
range_gt?: any;
range_gte?: any;
range_lt?: any;
range_lte?: any;
range_adjacent?: any;
overlaps?: any;
text_search?: string;
match?: Record<string, any>;
}
interface QueryOptions {
count?: 'exact' | 'planned' | 'estimated';
head?: boolean;
}
interface SelectOptions extends QueryOptions {
columns?: string;
}
interface InsertOptions extends QueryOptions {
returning?: 'minimal' | 'representation';
upsert?: boolean;
onConflict?: string;
}
interface UpdateOptions extends QueryOptions {
returning?: 'minimal' | 'representation';
}
interface DeleteOptions extends QueryOptions {
returning?: 'minimal' | 'representation';
}
interface AuthUser {
id: string;
email: string;
phone?: string;
name?: string;
avatar_url?: string;
created_at: string;
updated_at: string;
email_verified: boolean;
phone_verified: boolean;
app_metadata?: Record<string, any>;
user_metadata?: Record<string, any>;
}
interface AuthSession {
access_token: string;
refresh_token: string;
expires_in: number;
expires_at: number;
token_type: string;
user: AuthUser;
}
interface AuthResponse {
user?: AuthUser;
session?: AuthSession;
error?: string;
}
interface SignUpData {
email: string;
password: string;
name?: string;
phone?: string;
data?: Record<string, any>;
}
interface SignInData {
email: string;
password: string;
}
interface OAuthProvider {
provider: 'google' | 'github' | 'facebook';
redirectTo?: string;
scopes?: string;
}
declare class AuthClient {
private httpClient;
private currentSession;
constructor(httpClient: HttpClient$1);
signUp(data: SignUpData): Promise<AuthResponse>;
signIn(data: SignInData): Promise<AuthResponse>;
signOut(): Promise<void>;
getUser(): Promise<AuthUser | null>;
refreshSession(): Promise<AuthSession | null>;
resetPassword(email: string): Promise<void>;
updateUser(data: Partial<AuthUser>): Promise<AuthUser>;
getSession(): AuthSession | null;
onAuthStateChange(callback: (event: string, session: AuthSession | null) => void): () => void;
private setSession;
private clearSession;
private loadSession;
private handleAuthError;
}
declare class QueryBuilder<T = any> {
private httpClient;
private table;
private query;
constructor(httpClient: HttpClient$1, table: string);
select(columns?: string, options?: SelectOptions$1): this;
insert(data: Partial<T> | Partial<T>[], options?: InsertOptions$1): Promise<{
data: T[] | null;
error: EBaaSError$1 | null;
}>;
update(data: Partial<T>, options?: UpdateOptions$1): Promise<{
data: T[] | null;
error: EBaaSError$1 | null;
}>;
upsert(data: Partial<T> | Partial<T>[], options?: InsertOptions$1): Promise<{
data: T[] | null;
error: EBaaSError$1 | null;
}>;
delete(options?: DeleteOptions$1): Promise<{
data: T[] | null;
error: EBaaSError$1 | null;
}>;
eq(column: string, value: any): this;
neq(column: string, value: any): this;
gt(column: string, value: any): this;
gte(column: string, value: any): this;
lt(column: string, value: any): this;
lte(column: string, value: any): this;
like(column: string, pattern: string): this;
ilike(column: string, pattern: string): this;
is(column: string, value: any): this;
in(column: string, values: any[]): this;
contains(column: string, value: any): this;
match(query: Record<string, any>): this;
order(column: string, options?: {
ascending?: boolean;
}): this;
limit(count: number): this;
range(from: number, to: number): this;
execute(): Promise<{
data: T[] | null;
error: EBaaSError$1 | null;
count?: number;
}>;
single(): Promise<{
data: T | null;
error: EBaaSError$1 | null;
}>;
private executeQuery;
}
declare class DatabaseClient {
private httpClient;
constructor(httpClient: HttpClient$1);
from(table: string): QueryBuilder;
rpc(fn: string, args?: Record<string, any>): Promise<any>;
schema(schema: string): DatabaseClient;
}
interface StorageFile {
id: string;
name: string;
bucket_id: string;
path: string;
size: number;
mimetype: string;
etag: string;
created_at: string;
updated_at: string;
last_accessed_at?: string;
metadata?: Record<string, any>;
cache_control?: string;
content_encoding?: string;
content_disposition?: string;
content_language?: string;
}
interface Bucket {
id: string;
name: string;
owner: string;
public: boolean;
created_at: string;
updated_at: string;
allowed_mime_types?: string[];
file_size_limit?: number;
versioning_enabled?: boolean;
}
interface BucketOptions {
public?: boolean;
allowedMimeTypes?: string[];
fileSizeLimit?: number;
versioningEnabled?: boolean;
}
interface StorageUploadOptions {
cacheControl?: string;
contentType?: string;
upsert?: boolean;
metadata?: Record<string, any>;
duplex?: 'half';
}
interface StorageDownloadOptions {
transform?: {
width?: number;
height?: number;
resize?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside';
format?: 'jpeg' | 'png' | 'webp' | 'avif';
quality?: number;
};
}
interface StorageListOptions {
limit?: number;
offset?: number;
sortBy?: {
column: 'name' | 'updated_at' | 'created_at' | 'last_accessed_at';
order: 'asc' | 'desc';
};
search?: string;
}
interface StorageSignedUrlOptions {
download?: boolean;
transform?: {
width?: number;
height?: number;
resize?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside';
format?: 'jpeg' | 'png' | 'webp' | 'avif';
quality?: number;
};
}
interface FileUploadResponse {
id: string;
path: string;
fullPath: string;
key: string;
}
interface FileListResponse {
files: StorageFile[];
count: number;
hasMore: boolean;
}
interface SignedUrlResponse {
data: {
signedUrl: string;
path: string;
token: string;
};
}
interface PublicUrlResponse {
data: {
publicUrl: string;
};
}
interface StorageUsage {
total_size: number;
file_count: number;
bucket_count: number;
quota_used_percentage: number;
quota_limit?: number;
}
declare class StorageBucket {
private httpClient;
private bucketId;
constructor(httpClient: HttpClient$1, bucketId: string);
upload(path: string, file: File | Blob | ArrayBuffer | string, options?: StorageUploadOptions): Promise<{
data: FileUploadResponse | null;
error: EBaaSError$1 | null;
}>;
download(path: string, options?: StorageDownloadOptions): Promise<{
data: Blob | null;
error: EBaaSError$1 | null;
}>;
list(prefix?: string, options?: StorageListOptions): Promise<{
data: FileListResponse | null;
error: EBaaSError$1 | null;
}>;
remove(paths: string[]): Promise<{
data: {
message: string;
} | null;
error: EBaaSError$1 | null;
}>;
move(fromPath: string, toPath: string): Promise<{
data: {
message: string;
} | null;
error: EBaaSError$1 | null;
}>;
copy(fromPath: string, toPath: string): Promise<{
data: {
message: string;
} | null;
error: EBaaSError$1 | null;
}>;
createSignedUrl(path: string, expiresIn: number, options?: StorageSignedUrlOptions): Promise<{
data: SignedUrlResponse | null;
error: EBaaSError$1 | null;
}>;
getPublicUrl(path: string, options?: {
transform?: Record<string, any>;
}): PublicUrlResponse;
getFileInfo(path: string): Promise<{
data: StorageFile | null;
error: EBaaSError$1 | null;
}>;
updateFileMetadata(path: string, metadata: Record<string, any>): Promise<{
data: StorageFile | null;
error: EBaaSError$1 | null;
}>;
}
declare class StorageClient {
private httpClient;
constructor(httpClient: HttpClient$1);
from(bucketId: string): StorageBucket;
createBucket(id: string, options?: BucketOptions): Promise<{
data: Bucket | null;
error: EBaaSError$1 | null;
}>;
getBucket(id: string): Promise<{
data: Bucket | null;
error: EBaaSError$1 | null;
}>;
listBuckets(): Promise<{
data: Bucket[] | null;
error: EBaaSError$1 | null;
}>;
updateBucket(id: string, options: Partial<BucketOptions>): Promise<{
data: Bucket | null;
error: EBaaSError$1 | null;
}>;
deleteBucket(id: string): Promise<{
data: {
message: string;
} | null;
error: EBaaSError$1 | null;
}>;
getUsage(): Promise<{
data: StorageUsage | null;
error: EBaaSError$1 | null;
}>;
}
interface RealtimeEvent {
schema: string;
table: string;
commit_timestamp: string;
eventType: 'INSERT' | 'UPDATE' | 'DELETE';
new?: Record<string, any>;
old?: Record<string, any>;
errors?: string[];
}
interface ChannelSubscription {
unsubscribe: () => void;
}
interface PresenceState {
[key: string]: {
metas: Array<{
[key: string]: any;
phx_ref: string;
phx_ref_prev?: string;
}>;
};
}
interface PostgresChangesFilter {
event: '*' | 'INSERT' | 'UPDATE' | 'DELETE';
schema: string;
table?: string;
filter?: string;
}
interface BroadcastFilter {
event: string;
}
interface PresenceFilter {
event: 'sync' | 'join' | 'leave';
}
type ChannelState = 'closed' | 'errored' | 'joined' | 'joining' | 'leaving';
type RealtimeConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error';
interface RealtimeClientOptions {
heartbeatInterval?: number;
reconnectInterval?: number;
maxReconnectAttempts?: number;
socketOptions?: {
[key: string]: any;
};
}
declare class RealtimeChannel extends EventEmitter {
topic: string;
private socket;
private joinedOnce;
private state;
private subscriptions;
constructor(topic: string, socket: Socket | null);
subscribe(callback?: (status: 'SUBSCRIBED' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED') => void): RealtimeChannel;
onPostgresChanges(filter: PostgresChangesFilter, callback: (payload: RealtimeEvent) => void): ChannelSubscription;
onBroadcast(filter: BroadcastFilter, callback: (payload: any) => void): ChannelSubscription;
onPresence(filter: PresenceFilter, callback: (payload: PresenceState) => void): ChannelSubscription;
send(payload: {
type: 'broadcast';
event: string;
[key: string]: any;
}): Promise<'ok' | 'error' | 'timeout'>;
track(payload: Record<string, any>): Promise<'ok' | 'error' | 'timeout'>;
untrack(): Promise<'ok' | 'error' | 'timeout'>;
unsubscribe(): Promise<'ok' | 'error' | 'timeout'>;
_join(): void;
_rejoin(): void;
_trigger(event: string, payload: any): void;
_setState(state: ChannelState): void;
private makeRef;
getState(): ChannelState;
}
declare class RealtimeClient {
private socket;
private url;
private apiKey;
private options;
private channels;
private connectionState;
private reconnectAttempts;
private maxReconnectAttempts;
constructor(url: string, apiKey: string, options?: RealtimeClientOptions);
connect(): Promise<void>;
disconnect(): void;
channel(topic: string): RealtimeChannel;
removeChannel(channel: RealtimeChannel): void;
removeAllChannels(): void;
getChannels(): RealtimeChannel[];
isConnected(): boolean;
getConnectionState(): RealtimeConnectionState;
onConnectionStateChange(callback: (state: RealtimeConnectionState) => void): () => void;
private setupHeartbeat;
_getSocket(): Socket | null;
}
interface FunctionInvokeOptions {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
headers?: Record<string, string>;
body?: any;
region?: string;
}
interface FunctionResponse<T = any> {
data: T;
error?: string;
}
interface EdgeFunction {
id: string;
name: string;
slug: string;
status: 'active' | 'inactive' | 'deploying' | 'failed';
version: number;
created_at: string;
updated_at: string;
entrypoint?: string;
env?: Record<string, string>;
import_map?: Record<string, any>;
verify_jwt?: boolean;
execution_stats?: {
total_executions: number;
total_errors: number;
avg_execution_time: number;
last_execution: string;
};
}
interface FunctionListResponse {
functions: EdgeFunction[];
count: number;
}
interface FunctionDeployOptions {
code: string | File;
entrypoint?: string;
env?: Record<string, string>;
importMap?: Record<string, any>;
verify?: boolean;
}
interface FunctionDeployResponse {
id: string;
name: string;
version: number;
status: 'deploying' | 'active' | 'failed';
deployment_id: string;
created_at: string;
}
declare class FunctionsClient {
private httpClient;
constructor(httpClient: HttpClient$1);
invoke<T = any>(functionName: string, options?: FunctionInvokeOptions): Promise<{
data: T | null;
error: EBaaSError$1 | null;
}>;
list(): Promise<{
data: FunctionListResponse | null;
error: EBaaSError$1 | null;
}>;
get(functionName: string): Promise<{
data: EdgeFunction | null;
error: EBaaSError$1 | null;
}>;
deploy(functionName: string, options: FunctionDeployOptions): Promise<{
data: FunctionDeployResponse | null;
error: EBaaSError$1 | null;
}>;
delete(functionName: string): Promise<{
data: {
message: string;
} | null;
error: EBaaSError$1 | null;
}>;
updateEnv(functionName: string, env: Record<string, string>): Promise<{
data: EdgeFunction | null;
error: EBaaSError$1 | null;
}>;
getLogs(functionName: string, options?: {
limit?: number;
offset?: number;
level?: 'info' | 'warn' | 'error' | 'debug';
}): Promise<{
data: any[] | null;
error: EBaaSError$1 | null;
}>;
getMetrics(functionName: string, options?: {
period?: '1h' | '24h' | '7d' | '30d';
}): Promise<{
data: any | null;
error: EBaaSError$1 | null;
}>;
}
declare class EBaaSClient {
readonly auth: AuthClient;
readonly database: DatabaseClient;
readonly storage: StorageClient;
readonly realtime: RealtimeClient;
readonly functions: FunctionsClient;
private httpClient;
constructor(supabaseUrl: string, supabaseKey: string, options?: EBaaSClientOptions['options']);
from(table: string): QueryBuilder<any>;
rpc(fn: string, args?: Record<string, any>): Promise<any>;
bucket(id: string): StorageBucket;
channel(name: string): RealtimeChannel;
invoke(functionName: string, options?: any): Promise<{
data: any;
error: EBaaSError | null;
}>;
}
declare function createClient(supabaseUrl: string, supabaseKey: string, options?: EBaaSClientOptions['options']): EBaaSClient;
declare const version = "1.0.0";
export { AuthClient, DatabaseClient, EBaaSClient, EBaaSError, FunctionsClient, HttpClient, QueryBuilder, RealtimeChannel, RealtimeClient, StorageBucket, StorageClient, createClient, version };
export type { AuthResponse, AuthSession, AuthUser, BroadcastFilter, Bucket, BucketOptions, ChannelSubscription, DatabaseFilters, DeleteOptions, EBaaSClientOptions, EdgeFunction, FunctionDeployOptions, FunctionInvokeOptions, FunctionListResponse, FunctionResponse, InsertOptions, OAuthProvider, PostgresChangesFilter, PresenceFilter, PresenceState, QueryOptions, RealtimeClientOptions, RealtimeEvent, SelectOptions, SignInData, SignUpData, StorageDownloadOptions, StorageFile, StorageListOptions, StorageUploadOptions, StorageUsage, UpdateOptions };