@allanfsouza/aether-sdk 1.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth.d.ts +2 -18
- package/dist/auth.js +16 -23
- package/dist/database.d.ts +30 -27
- package/dist/database.js +75 -55
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +42 -0
- package/dist/functions.d.ts +8 -0
- package/dist/functions.js +17 -0
- package/dist/http-client.d.ts +3 -5
- package/dist/http-client.js +11 -7
- package/dist/index.d.ts +12 -6
- package/dist/index.js +12 -7
- package/dist/storage.d.ts +19 -11
- package/dist/storage.js +50 -25
- package/errors.ts +46 -0
- package/package.json +10 -8
- package/src/auth.ts +22 -31
- package/src/database.ts +100 -70
- package/src/errors.ts +50 -0
- package/src/functions.ts +31 -0
- package/src/http-client.ts +17 -9
- package/src/index.ts +24 -11
- package/src/storage.ts +53 -25
- package/tsconfig.json +16 -9
package/dist/auth.d.ts
CHANGED
|
@@ -1,32 +1,16 @@
|
|
|
1
1
|
import type { AxiosInstance } from "axios";
|
|
2
2
|
import type { PlataformaClient } from "./index.js";
|
|
3
|
-
/**
|
|
4
|
-
* Módulo de Autenticação
|
|
5
|
-
* Lida com login, registro e gerenciamento de token.
|
|
6
|
-
*/
|
|
7
3
|
export declare class AuthModule {
|
|
8
4
|
private client;
|
|
9
5
|
private http;
|
|
10
6
|
constructor(client: PlataformaClient, http: AxiosInstance);
|
|
11
|
-
/**
|
|
12
|
-
* Autentica um usuário e armazena o token no SDK.
|
|
13
|
-
* @param email O e-mail do usuário
|
|
14
|
-
* @param password A senha do usuário
|
|
15
|
-
* @returns O objeto do usuário e o token
|
|
16
|
-
*/
|
|
17
7
|
login(email: string, password: string): Promise<any>;
|
|
18
|
-
/**
|
|
19
|
-
* Registra um novo usuário e já o loga.
|
|
20
|
-
* @param credentials Nome, email e senha
|
|
21
|
-
* @returns O objeto do usuário e o token
|
|
22
|
-
*/
|
|
23
8
|
register(credentials: {
|
|
24
9
|
name: string;
|
|
25
10
|
email: string;
|
|
26
11
|
password: string;
|
|
27
12
|
}): Promise<any>;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
*/
|
|
13
|
+
forgotPassword(email: string): Promise<any>;
|
|
14
|
+
resetPassword(token: string, newPassword: string): Promise<any>;
|
|
31
15
|
logout(): void;
|
|
32
16
|
}
|
package/dist/auth.js
CHANGED
|
@@ -1,39 +1,27 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Módulo de Autenticação
|
|
3
|
-
* Lida com login, registro e gerenciamento de token.
|
|
4
|
-
*/
|
|
5
1
|
export class AuthModule {
|
|
6
2
|
constructor(client, http) {
|
|
7
3
|
this.client = client;
|
|
8
4
|
this.http = http;
|
|
9
5
|
}
|
|
10
|
-
/**
|
|
11
|
-
* Autentica um usuário e armazena o token no SDK.
|
|
12
|
-
* @param email O e-mail do usuário
|
|
13
|
-
* @param password A senha do usuário
|
|
14
|
-
* @returns O objeto do usuário e o token
|
|
15
|
-
*/
|
|
16
6
|
async login(email, password) {
|
|
17
7
|
try {
|
|
18
8
|
const { data } = await this.http.post("/auth/login", { email, password });
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
9
|
+
if (data.token) {
|
|
10
|
+
this.client.setToken(data.token);
|
|
11
|
+
}
|
|
12
|
+
return data;
|
|
22
13
|
}
|
|
23
14
|
catch (e) {
|
|
24
|
-
this.client.setToken(null);
|
|
15
|
+
this.client.setToken(null);
|
|
25
16
|
throw e;
|
|
26
17
|
}
|
|
27
18
|
}
|
|
28
|
-
/**
|
|
29
|
-
* Registra um novo usuário e já o loga.
|
|
30
|
-
* @param credentials Nome, email e senha
|
|
31
|
-
* @returns O objeto do usuário e o token
|
|
32
|
-
*/
|
|
33
19
|
async register(credentials) {
|
|
34
20
|
try {
|
|
35
21
|
const { data } = await this.http.post("/auth/register", credentials);
|
|
36
|
-
|
|
22
|
+
if (data.token) {
|
|
23
|
+
this.client.setToken(data.token);
|
|
24
|
+
}
|
|
37
25
|
return data;
|
|
38
26
|
}
|
|
39
27
|
catch (e) {
|
|
@@ -41,9 +29,14 @@ export class AuthModule {
|
|
|
41
29
|
throw e;
|
|
42
30
|
}
|
|
43
31
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
32
|
+
async forgotPassword(email) {
|
|
33
|
+
const { data } = await this.http.post("/auth/forgot-password", { email });
|
|
34
|
+
return data;
|
|
35
|
+
}
|
|
36
|
+
async resetPassword(token, newPassword) {
|
|
37
|
+
const { data } = await this.http.post("/auth/reset-password", { token, newPassword });
|
|
38
|
+
return data;
|
|
39
|
+
}
|
|
47
40
|
logout() {
|
|
48
41
|
this.client.setToken(null);
|
|
49
42
|
}
|
package/dist/database.d.ts
CHANGED
|
@@ -1,59 +1,62 @@
|
|
|
1
1
|
import type { AxiosInstance } from "axios";
|
|
2
2
|
import type { PlataformaClient } from "./index.js";
|
|
3
|
+
export type ListOptions<T> = {
|
|
4
|
+
filter?: Partial<T>;
|
|
5
|
+
sort?: {
|
|
6
|
+
field: keyof T & string;
|
|
7
|
+
order: "ASC" | "DESC";
|
|
8
|
+
};
|
|
9
|
+
};
|
|
3
10
|
/**
|
|
4
|
-
* Módulo de Banco de Dados
|
|
5
|
-
* Ponto de entrada para acessar as coleções.
|
|
11
|
+
* Módulo de Banco de Dados
|
|
6
12
|
*/
|
|
7
13
|
export declare class DatabaseModule {
|
|
8
14
|
private client;
|
|
9
15
|
private http;
|
|
10
16
|
constructor(client: PlataformaClient, http: AxiosInstance);
|
|
11
17
|
/**
|
|
12
|
-
* Seleciona uma coleção de dados
|
|
13
|
-
*
|
|
14
|
-
* @
|
|
18
|
+
* Seleciona uma coleção de dados.
|
|
19
|
+
* [PREMIUM] Suporta Generics <T> para tipagem forte.
|
|
20
|
+
* * @example client.db.collection<Product>('products')
|
|
15
21
|
*/
|
|
16
|
-
collection(collectionName: string): CollectionReference
|
|
22
|
+
collection<T = any>(collectionName: string): CollectionReference<T>;
|
|
17
23
|
}
|
|
18
24
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
25
|
+
* Referência a uma coleção específica.
|
|
26
|
+
* O <T> define o formato dos dados (ex: interface User).
|
|
21
27
|
*/
|
|
22
|
-
declare class CollectionReference {
|
|
28
|
+
declare class CollectionReference<T> {
|
|
23
29
|
private client;
|
|
24
30
|
private http;
|
|
25
31
|
private collectionName;
|
|
26
32
|
private wsUrl;
|
|
27
33
|
constructor(client: PlataformaClient, http: AxiosInstance, name: string);
|
|
28
34
|
/**
|
|
29
|
-
* Lista
|
|
30
|
-
*
|
|
35
|
+
* Lista documentos da coleção com filtros opcionais.
|
|
36
|
+
* @param options Filtros e Ordenação
|
|
31
37
|
*/
|
|
32
|
-
list(): Promise<
|
|
38
|
+
list(options?: ListOptions<T>): Promise<T[]>;
|
|
33
39
|
/**
|
|
34
|
-
*
|
|
35
|
-
* (POST /v1/db/tasks)
|
|
36
|
-
* @param newData O objeto de dados a ser criado
|
|
40
|
+
* Busca um documento pelo ID.
|
|
37
41
|
*/
|
|
38
|
-
|
|
42
|
+
get(id: string): Promise<T>;
|
|
43
|
+
/**
|
|
44
|
+
* Cria um novo documento.
|
|
45
|
+
* O Partial<T> permite criar sem passar campos gerados (como id, createdAt).
|
|
46
|
+
*/
|
|
47
|
+
create(newData: Partial<T>): Promise<T>;
|
|
39
48
|
/**
|
|
40
49
|
* Atualiza um documento existente.
|
|
41
|
-
* (PUT /v1/db/tasks/:id)
|
|
42
|
-
* @param id O ID do documento
|
|
43
|
-
* @param updates Os campos a serem atualizados
|
|
44
50
|
*/
|
|
45
|
-
update(id: string, updates:
|
|
51
|
+
update(id: string, updates: Partial<T>): Promise<T>;
|
|
46
52
|
/**
|
|
47
53
|
* Deleta um documento.
|
|
48
|
-
* (DELETE /v1/db/tasks/:id)
|
|
49
|
-
* @param id O ID do documento
|
|
50
54
|
*/
|
|
51
|
-
delete(id: string): Promise<
|
|
55
|
+
delete(id: string): Promise<boolean>;
|
|
52
56
|
/**
|
|
53
|
-
* Inscreve-se para mudanças em tempo real
|
|
54
|
-
*
|
|
55
|
-
* @returns Uma função 'unsubscribe' para fechar a conexão
|
|
57
|
+
* Inscreve-se para mudanças em tempo real.
|
|
58
|
+
* O callback recebe os dados já tipados como T.
|
|
56
59
|
*/
|
|
57
|
-
subscribe(callback: (action: "create" | "update" | "delete", data:
|
|
60
|
+
subscribe(callback: (action: "create" | "update" | "delete", data: T) => void): () => void;
|
|
58
61
|
}
|
|
59
62
|
export {};
|
package/dist/database.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import WebSocket from "ws";
|
|
2
2
|
/**
|
|
3
|
-
* Módulo de Banco de Dados
|
|
4
|
-
* Ponto de entrada para acessar as coleções.
|
|
3
|
+
* Módulo de Banco de Dados
|
|
5
4
|
*/
|
|
6
5
|
export class DatabaseModule {
|
|
7
6
|
constructor(client, http) {
|
|
@@ -9,98 +8,119 @@ export class DatabaseModule {
|
|
|
9
8
|
this.http = http;
|
|
10
9
|
}
|
|
11
10
|
/**
|
|
12
|
-
* Seleciona uma coleção de dados
|
|
13
|
-
*
|
|
14
|
-
* @
|
|
11
|
+
* Seleciona uma coleção de dados.
|
|
12
|
+
* [PREMIUM] Suporta Generics <T> para tipagem forte.
|
|
13
|
+
* * @example client.db.collection<Product>('products')
|
|
15
14
|
*/
|
|
16
15
|
collection(collectionName) {
|
|
17
16
|
return new CollectionReference(this.client, this.http, collectionName);
|
|
18
17
|
}
|
|
19
18
|
}
|
|
20
19
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* Referência a uma coleção específica.
|
|
21
|
+
* O <T> define o formato dos dados (ex: interface User).
|
|
23
22
|
*/
|
|
24
23
|
class CollectionReference {
|
|
25
24
|
constructor(client, http, name) {
|
|
26
25
|
this.client = client;
|
|
27
26
|
this.http = http;
|
|
28
27
|
this.collectionName = name;
|
|
29
|
-
//
|
|
30
|
-
|
|
28
|
+
// Ajusta protocolo para WS/WSS
|
|
29
|
+
const protocol = client.apiUrl.startsWith("https") ? "wss" : "ws";
|
|
30
|
+
this.wsUrl = client.apiUrl.replace(/^https?/, protocol);
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
33
|
-
* Lista
|
|
34
|
-
*
|
|
33
|
+
* Lista documentos da coleção com filtros opcionais.
|
|
34
|
+
* @param options Filtros e Ordenação
|
|
35
35
|
*/
|
|
36
|
-
async list() {
|
|
37
|
-
const
|
|
38
|
-
|
|
36
|
+
async list(options) {
|
|
37
|
+
const params = {};
|
|
38
|
+
// Converte os objetos do SDK para strings que o Backend entende
|
|
39
|
+
if (options?.filter) {
|
|
40
|
+
params.filter = JSON.stringify(options.filter);
|
|
41
|
+
}
|
|
42
|
+
if (options?.sort) {
|
|
43
|
+
// Backend espera formato array: ["campo", "DESC"]
|
|
44
|
+
params.sort = JSON.stringify([options.sort.field, options.sort.order]);
|
|
45
|
+
}
|
|
46
|
+
const { data } = await this.http.get(`/db/${this.collectionName}`, {
|
|
47
|
+
params,
|
|
48
|
+
});
|
|
49
|
+
return data.data;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Busca um documento pelo ID.
|
|
53
|
+
*/
|
|
54
|
+
async get(id) {
|
|
55
|
+
const { data } = await this.http.get(`/db/${this.collectionName}/${id}`);
|
|
56
|
+
return data.data;
|
|
39
57
|
}
|
|
40
58
|
/**
|
|
41
|
-
* Cria um novo documento
|
|
42
|
-
* (
|
|
43
|
-
* @param newData O objeto de dados a ser criado
|
|
59
|
+
* Cria um novo documento.
|
|
60
|
+
* O Partial<T> permite criar sem passar campos gerados (como id, createdAt).
|
|
44
61
|
*/
|
|
45
62
|
async create(newData) {
|
|
46
63
|
const { data } = await this.http.post(`/db/${this.collectionName}`, newData);
|
|
47
|
-
return data.data;
|
|
64
|
+
return data.data;
|
|
48
65
|
}
|
|
49
66
|
/**
|
|
50
67
|
* Atualiza um documento existente.
|
|
51
|
-
* (PUT /v1/db/tasks/:id)
|
|
52
|
-
* @param id O ID do documento
|
|
53
|
-
* @param updates Os campos a serem atualizados
|
|
54
68
|
*/
|
|
55
69
|
async update(id, updates) {
|
|
56
70
|
const { data } = await this.http.put(`/db/${this.collectionName}/${id}`, updates);
|
|
57
|
-
return data.data;
|
|
71
|
+
return data.data;
|
|
58
72
|
}
|
|
59
73
|
/**
|
|
60
74
|
* Deleta um documento.
|
|
61
|
-
* (DELETE /v1/db/tasks/:id)
|
|
62
|
-
* @param id O ID do documento
|
|
63
75
|
*/
|
|
64
76
|
async delete(id) {
|
|
65
|
-
|
|
66
|
-
return
|
|
77
|
+
await this.http.delete(`/db/${this.collectionName}/${id}`);
|
|
78
|
+
return true;
|
|
67
79
|
}
|
|
68
80
|
/**
|
|
69
|
-
* Inscreve-se para mudanças em tempo real
|
|
70
|
-
*
|
|
71
|
-
* @returns Uma função 'unsubscribe' para fechar a conexão
|
|
81
|
+
* Inscreve-se para mudanças em tempo real.
|
|
82
|
+
* O callback recebe os dados já tipados como T.
|
|
72
83
|
*/
|
|
73
84
|
subscribe(callback) {
|
|
74
85
|
const token = this.client.getToken();
|
|
75
86
|
const projectId = this.client.projectId;
|
|
76
87
|
if (!token || !projectId) {
|
|
77
|
-
|
|
88
|
+
console.warn("[SDK] Realtime falhou: Token ou ProjectId ausentes.");
|
|
89
|
+
return () => { };
|
|
78
90
|
}
|
|
79
|
-
// Constrói a URL: ws://localhost:3000/v1/db/subscribe/tasks?token=...&projectId=...
|
|
80
91
|
const url = `${this.wsUrl}/v1/db/subscribe/${this.collectionName}?token=${token}&projectId=${projectId}`;
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
92
|
+
let ws = null;
|
|
93
|
+
try {
|
|
94
|
+
ws = new WebSocket(url);
|
|
95
|
+
ws.onopen = () => {
|
|
96
|
+
// Conectado
|
|
97
|
+
};
|
|
98
|
+
ws.onmessage = (event) => {
|
|
99
|
+
try {
|
|
100
|
+
const raw = event.data?.toString() || event.toString();
|
|
101
|
+
if (raw === "pong")
|
|
102
|
+
return;
|
|
103
|
+
const payload = JSON.parse(raw);
|
|
104
|
+
callback(payload.action, payload.data);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
// Erro silencioso de parse
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
// Mantém a conexão viva (Heartbeat)
|
|
111
|
+
const pingInterval = setInterval(() => {
|
|
112
|
+
if (ws?.readyState === WebSocket.OPEN)
|
|
113
|
+
ws.send("ping");
|
|
114
|
+
}, 30000);
|
|
115
|
+
return () => {
|
|
116
|
+
clearInterval(pingInterval);
|
|
117
|
+
if (ws)
|
|
118
|
+
ws.close();
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
console.error("[SDK] Erro WS:", err);
|
|
123
|
+
return () => { };
|
|
124
|
+
}
|
|
105
125
|
}
|
|
106
126
|
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare class AetherError extends Error {
|
|
2
|
+
code: string;
|
|
3
|
+
message: string;
|
|
4
|
+
status?: number | undefined;
|
|
5
|
+
details?: any | undefined;
|
|
6
|
+
constructor(code: string, message: string, status?: number | undefined, details?: any | undefined);
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Converte qualquer erro vindo do Axios em um AetherError padronizado.
|
|
10
|
+
* Essa função é pensada para ser usada no interceptor de responses.
|
|
11
|
+
*/
|
|
12
|
+
export declare function handleAxiosError(error: any): never;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
export class AetherError extends Error {
|
|
3
|
+
constructor(code, message, status, details) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.message = message;
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.details = details;
|
|
9
|
+
this.name = "AetherError";
|
|
10
|
+
// Garante que instanceof AetherError funcione mesmo em cenários com transpile/bundler
|
|
11
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Converte qualquer erro vindo do Axios em um AetherError padronizado.
|
|
16
|
+
* Essa função é pensada para ser usada no interceptor de responses.
|
|
17
|
+
*/
|
|
18
|
+
export function handleAxiosError(error) {
|
|
19
|
+
// Erro com resposta do servidor (4xx, 5xx)
|
|
20
|
+
if (error && error.response) {
|
|
21
|
+
const data = error.response.data;
|
|
22
|
+
const message = data?.error || data?.message || "Erro desconhecido na API";
|
|
23
|
+
const status = error.response.status;
|
|
24
|
+
let code = "api_error";
|
|
25
|
+
if (status === 401)
|
|
26
|
+
code = "unauthorized";
|
|
27
|
+
if (status === 403)
|
|
28
|
+
code = "permission_denied";
|
|
29
|
+
if (status === 404)
|
|
30
|
+
code = "not_found";
|
|
31
|
+
if (status === 429)
|
|
32
|
+
code = "rate_limit_exceeded";
|
|
33
|
+
throw new AetherError(code, message, status, data);
|
|
34
|
+
}
|
|
35
|
+
// Erro de rede (sem resposta do servidor)
|
|
36
|
+
if (error && error.request && !error.response) {
|
|
37
|
+
throw new AetherError("network_error", "Não foi possível conectar ao servidor Aether.", 0);
|
|
38
|
+
}
|
|
39
|
+
// Erro de configuração / código do cliente
|
|
40
|
+
const fallbackMessage = (error && error.message) || "Erro interno no cliente SDK.";
|
|
41
|
+
throw new AetherError("client_error", fallbackMessage);
|
|
42
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AxiosInstance } from "axios";
|
|
2
|
+
import type { PlataformaClient } from "./index.js";
|
|
3
|
+
export declare class FunctionsModule {
|
|
4
|
+
private client;
|
|
5
|
+
private http;
|
|
6
|
+
constructor(client: PlataformaClient, http: AxiosInstance);
|
|
7
|
+
invoke<T = any>(functionName: string, body?: any, method?: "GET" | "POST" | "PUT" | "DELETE"): Promise<T>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export class FunctionsModule {
|
|
2
|
+
constructor(client, http) {
|
|
3
|
+
this.client = client;
|
|
4
|
+
this.http = http;
|
|
5
|
+
}
|
|
6
|
+
async invoke(functionName, body, method) {
|
|
7
|
+
const projectId = this.client.projectId;
|
|
8
|
+
const cleanName = functionName.replace(/^\//, "");
|
|
9
|
+
const finalMethod = method || (body ? "POST" : "GET");
|
|
10
|
+
const response = await this.http.request({
|
|
11
|
+
url: `/functions/http/${projectId}/${cleanName}`,
|
|
12
|
+
method: finalMethod,
|
|
13
|
+
data: body,
|
|
14
|
+
});
|
|
15
|
+
return response.data;
|
|
16
|
+
}
|
|
17
|
+
}
|
package/dist/http-client.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { type AxiosInstance } from "axios";
|
|
2
|
-
import { PlataformaClient } from "./index.js";
|
|
2
|
+
import type { PlataformaClient } from "./index.js";
|
|
3
3
|
/**
|
|
4
4
|
* Cria uma instância do Axios pré-configurada.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* * @param client A instância principal do PlataformaClient
|
|
8
|
-
* @returns Uma instância configurada do Axios
|
|
5
|
+
* - Injeta automaticamente headers de Auth e Projeto.
|
|
6
|
+
* - Converte erros em AetherError.
|
|
9
7
|
*/
|
|
10
8
|
export declare function createHttpClient(client: PlataformaClient): AxiosInstance;
|
package/dist/http-client.js
CHANGED
|
@@ -1,27 +1,31 @@
|
|
|
1
1
|
// src/http-client.ts
|
|
2
2
|
import axios from "axios";
|
|
3
|
+
import { handleAxiosError } from "./errors.js";
|
|
3
4
|
/**
|
|
4
5
|
* Cria uma instância do Axios pré-configurada.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* * @param client A instância principal do PlataformaClient
|
|
8
|
-
* @returns Uma instância configurada do Axios
|
|
6
|
+
* - Injeta automaticamente headers de Auth e Projeto.
|
|
7
|
+
* - Converte erros em AetherError.
|
|
9
8
|
*/
|
|
10
9
|
export function createHttpClient(client) {
|
|
11
10
|
const http = axios.create({
|
|
12
|
-
|
|
11
|
+
// Adiciona o /v1 automaticamente em todas as chamadas do SDK
|
|
12
|
+
baseURL: `${client.apiUrl}/v1`,
|
|
13
|
+
headers: {
|
|
14
|
+
"Content-Type": "application/json",
|
|
15
|
+
},
|
|
13
16
|
});
|
|
17
|
+
// Interceptor de REQUEST
|
|
14
18
|
http.interceptors.request.use((config) => {
|
|
15
|
-
// 1. Pega o token atual do cliente
|
|
16
19
|
const token = client.getToken();
|
|
17
20
|
if (token) {
|
|
18
21
|
config.headers.Authorization = `Bearer ${token}`;
|
|
19
22
|
}
|
|
20
|
-
// 2. Pega o ID do projeto
|
|
21
23
|
if (client.projectId) {
|
|
22
24
|
config.headers["X-Project-ID"] = client.projectId;
|
|
23
25
|
}
|
|
24
26
|
return config;
|
|
25
27
|
});
|
|
28
|
+
// Interceptor de RESPONSE
|
|
29
|
+
http.interceptors.response.use((response) => response, (error) => handleAxiosError(error));
|
|
26
30
|
return http;
|
|
27
31
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
import { AuthModule } from "./auth.js";
|
|
2
2
|
import { DatabaseModule } from "./database.js";
|
|
3
3
|
import { StorageModule } from "./storage.js";
|
|
4
|
-
|
|
4
|
+
import { FunctionsModule } from "./functions.js";
|
|
5
|
+
/**
|
|
6
|
+
* Configuração usada para criar o cliente principal da plataforma.
|
|
7
|
+
*/
|
|
8
|
+
export type ClientConfig = {
|
|
5
9
|
apiUrl: string;
|
|
6
10
|
projectId: string;
|
|
7
11
|
};
|
|
8
12
|
/**
|
|
9
|
-
* O cliente principal da Plataforma API.
|
|
10
|
-
* Ponto de entrada para todos os módulos (Auth, DB, Storage).
|
|
13
|
+
* O cliente principal da Plataforma API (Aether).
|
|
14
|
+
* Ponto de entrada para todos os módulos (Auth, DB, Storage, Functions).
|
|
11
15
|
*/
|
|
12
16
|
export declare class PlataformaClient {
|
|
13
17
|
auth: AuthModule;
|
|
14
18
|
db: DatabaseModule;
|
|
15
19
|
storage: StorageModule;
|
|
20
|
+
functions: FunctionsModule;
|
|
16
21
|
apiUrl: string;
|
|
17
22
|
projectId: string;
|
|
18
23
|
private http;
|
|
@@ -20,13 +25,14 @@ export declare class PlataformaClient {
|
|
|
20
25
|
constructor(config: ClientConfig);
|
|
21
26
|
/**
|
|
22
27
|
* Armazena o token de autenticação em memória.
|
|
23
|
-
*
|
|
28
|
+
* Chamado automaticamente pelo AuthModule após login/registro.
|
|
24
29
|
*/
|
|
25
30
|
setToken(token: string | null): void;
|
|
26
31
|
/**
|
|
27
32
|
* Recupera o token de autenticação atual.
|
|
28
|
-
*
|
|
33
|
+
* Usado pelo http-client para injetar o header Authorization.
|
|
29
34
|
*/
|
|
30
35
|
getToken(): string | null;
|
|
31
36
|
}
|
|
32
|
-
export {};
|
|
37
|
+
export { AetherError } from "./errors.js";
|
|
38
|
+
export type { ListOptions } from "./database.js";
|
package/dist/index.js
CHANGED
|
@@ -2,9 +2,10 @@ import { createHttpClient } from "./http-client.js";
|
|
|
2
2
|
import { AuthModule } from "./auth.js";
|
|
3
3
|
import { DatabaseModule } from "./database.js";
|
|
4
4
|
import { StorageModule } from "./storage.js";
|
|
5
|
+
import { FunctionsModule } from "./functions.js";
|
|
5
6
|
/**
|
|
6
|
-
* O cliente principal da Plataforma API.
|
|
7
|
-
* Ponto de entrada para todos os módulos (Auth, DB, Storage).
|
|
7
|
+
* O cliente principal da Plataforma API (Aether).
|
|
8
|
+
* Ponto de entrada para todos os módulos (Auth, DB, Storage, Functions).
|
|
8
9
|
*/
|
|
9
10
|
export class PlataformaClient {
|
|
10
11
|
constructor(config) {
|
|
@@ -12,28 +13,32 @@ export class PlataformaClient {
|
|
|
12
13
|
if (!config.apiUrl || !config.projectId) {
|
|
13
14
|
throw new Error("apiUrl e projectId são obrigatórios.");
|
|
14
15
|
}
|
|
15
|
-
|
|
16
|
+
// Normaliza apiUrl removendo barra final, se houver
|
|
17
|
+
this.apiUrl = config.apiUrl.replace(/\/$/, "");
|
|
16
18
|
this.projectId = config.projectId;
|
|
17
|
-
// Inicializa o cliente HTTP (passando
|
|
19
|
+
// Inicializa o cliente HTTP (passando a própria instância)
|
|
18
20
|
this.http = createHttpClient(this);
|
|
19
|
-
// Inicializa os módulos
|
|
21
|
+
// Inicializa os módulos de alto nível
|
|
20
22
|
this.auth = new AuthModule(this, this.http);
|
|
21
23
|
this.db = new DatabaseModule(this, this.http);
|
|
22
24
|
this.storage = new StorageModule(this, this.http);
|
|
25
|
+
this.functions = new FunctionsModule(this, this.http);
|
|
23
26
|
}
|
|
24
27
|
// --- Gerenciamento de Token ---
|
|
25
28
|
/**
|
|
26
29
|
* Armazena o token de autenticação em memória.
|
|
27
|
-
*
|
|
30
|
+
* Chamado automaticamente pelo AuthModule após login/registro.
|
|
28
31
|
*/
|
|
29
32
|
setToken(token) {
|
|
30
33
|
this._token = token;
|
|
31
34
|
}
|
|
32
35
|
/**
|
|
33
36
|
* Recupera o token de autenticação atual.
|
|
34
|
-
*
|
|
37
|
+
* Usado pelo http-client para injetar o header Authorization.
|
|
35
38
|
*/
|
|
36
39
|
getToken() {
|
|
37
40
|
return this._token;
|
|
38
41
|
}
|
|
39
42
|
}
|
|
43
|
+
// Re-exports convenientes para quem consome o SDK
|
|
44
|
+
export { AetherError } from "./errors.js";
|
package/dist/storage.d.ts
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
1
|
import type { AxiosInstance } from "axios";
|
|
2
2
|
import type { PlataformaClient } from "./index.js";
|
|
3
|
-
/**
|
|
4
|
-
* Módulo de Storage
|
|
5
|
-
* Lida com upload e download de arquivos.
|
|
6
|
-
*/
|
|
7
3
|
export declare class StorageModule {
|
|
8
4
|
private client;
|
|
9
5
|
private http;
|
|
10
6
|
constructor(client: PlataformaClient, http: AxiosInstance);
|
|
11
7
|
/**
|
|
12
|
-
* Faz o upload de um arquivo
|
|
13
|
-
*
|
|
14
|
-
* @param
|
|
15
|
-
* @param
|
|
16
|
-
* @param
|
|
17
|
-
* @returns O objeto do arquivo criado no banco
|
|
8
|
+
* Faz o upload de um arquivo.
|
|
9
|
+
* @param file Arquivo (Browser: File, Node: Buffer)
|
|
10
|
+
* @param fileName Nome do arquivo (ex: 'foto.jpg')
|
|
11
|
+
* @param contentType MIME Type (ex: 'image/jpeg')
|
|
12
|
+
* @param folder (Opcional) Pasta de destino (ex: 'usuarios/123/')
|
|
18
13
|
*/
|
|
19
|
-
upload(file: File | Buffer, fileName: string, contentType: string): Promise<
|
|
14
|
+
upload(file: File | Buffer | Blob, fileName: string, contentType: string, folder?: string): Promise<{
|
|
15
|
+
id: any;
|
|
16
|
+
key: any;
|
|
17
|
+
downloadUrl: any;
|
|
18
|
+
url: any;
|
|
19
|
+
}>;
|
|
20
|
+
/**
|
|
21
|
+
* Lista arquivos de uma pasta.
|
|
22
|
+
*/
|
|
23
|
+
list(folder?: string): Promise<any>;
|
|
24
|
+
/**
|
|
25
|
+
* Deleta um arquivo pelo ID.
|
|
26
|
+
*/
|
|
27
|
+
delete(fileId: string): Promise<boolean>;
|
|
20
28
|
}
|