@bagelink/sdk 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Neveh Allon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @bagelink/vue
2
+
3
+ Features:
4
+
5
+ - Build with [unbuild](https://github.com/unjs/unbuild)
6
+ - File-to-file transpilation via [mkdist](https://github.com/unjs/mkdist)
7
+ - Playground with [vite](https://vitejs.dev/)
8
+
9
+ ## Usage
10
+
11
+ Use component globally
12
+
13
+ ```ts
14
+ // src/main.ts
15
+ import { createApp } from 'vue';
16
+ import { BagelVue } from '@bagel/vue';
17
+
18
+ import App from './App.vue';
19
+
20
+ const BagelConfig = {
21
+ host: import.meta.env.VITE_BASE_URL,
22
+ // eslint-disable-next-line n/handle-callback-err
23
+ onError: (err: any) => {
24
+ // handle error
25
+ // example:
26
+ // useToast().error(`${$t('anErrorOccurred')}: ${err?.response?.data?.detail || err.message}`);
27
+ },
28
+ };
29
+
30
+ const app = createApp(App);
31
+ app.use(head as Plugin);
32
+
33
+ app.mount('#app');
34
+ ```
35
+
36
+ Import component
37
+
38
+ ```vue
39
+ <script setup lang="ts">
40
+ import { useBagel } from '@bagel/vue';
41
+
42
+ const bagel = useBagel();
43
+ </script>
44
+
45
+ <!-- OR -->
46
+ <script lang="ts">
47
+ export default defineComponent({
48
+ onMounted() {
49
+ console.log(this.$bagel.host)
50
+ },
51
+ });
52
+ </script>
53
+
54
+ <!-- OR -->
55
+ <template>
56
+ <div>
57
+ {{ $bagel.host }}
58
+ </div>
59
+ </template>
60
+ ```
61
+
62
+
63
+ ## License
64
+
65
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,235 @@
1
+ 'use strict';
2
+
3
+ const ax = require('axios');
4
+
5
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
6
+
7
+ const ax__default = /*#__PURE__*/_interopDefaultCompat(ax);
8
+
9
+ var __defProp = Object.defineProperty;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __publicField = (obj, key, value) => {
12
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
13
+ return value;
14
+ };
15
+ const axios = ax__default.create({
16
+ // withCredentials to true to send cookies with requests
17
+ withCredentials: true
18
+ });
19
+ class DataRequest {
20
+ constructor(table, bagel) {
21
+ __publicField(this, "data_table");
22
+ __publicField(this, "bagel");
23
+ __publicField(this, "itemID");
24
+ __publicField(this, "_filter", {});
25
+ this.data_table = table;
26
+ this.bagel = bagel;
27
+ this.itemID = "";
28
+ }
29
+ async post(item) {
30
+ if (!this.data_table)
31
+ throw new Error("Data table not set");
32
+ const { data } = await axios.post(
33
+ `${this.bagel.host}/data/${this.data_table}`,
34
+ item
35
+ );
36
+ return data;
37
+ }
38
+ filter(filter) {
39
+ this._filter = filter;
40
+ return this;
41
+ }
42
+ async get() {
43
+ if (!this.data_table)
44
+ throw new Error("Data table not set");
45
+ const filterStr = Object.keys(this._filter).length ? `?filter={${Object.entries(this._filter).map(([k, v]) => `${k}:${v}`).join(",")}}` : "";
46
+ const url = `${this.bagel.host}/data/${this.data_table}${this.itemID ? `/${this.itemID}` : ""}${filterStr}`;
47
+ try {
48
+ const { data } = await axios.get(url);
49
+ return data;
50
+ } catch (err) {
51
+ console.log(err);
52
+ this.bagel.onError?.(err);
53
+ return void 0;
54
+ }
55
+ }
56
+ item(id) {
57
+ this.itemID = id;
58
+ return this;
59
+ }
60
+ async delete() {
61
+ if (!this.data_table)
62
+ throw new Error("Data table not set");
63
+ const { data } = await axios.delete(
64
+ `${this.bagel.host}/data/${this.data_table}/${this.itemID}`
65
+ );
66
+ return data;
67
+ }
68
+ async put(updatedItem) {
69
+ const { data_table, itemID, bagel } = this;
70
+ if (!data_table)
71
+ throw new Error("Data table not set");
72
+ if (!itemID)
73
+ throw new Error("Item ID not set");
74
+ const { data } = await axios.put(
75
+ `${bagel.host}/data/${data_table}/${itemID}`,
76
+ updatedItem
77
+ );
78
+ return data;
79
+ }
80
+ }
81
+ function responses(key) {
82
+ const res = {
83
+ LOGIN_BAD_CREDENTIALS: "Invalid username or password",
84
+ RESET_PASSWORD_BAD_TOKEN: "This reset password link is invalid or expired."
85
+ };
86
+ return res[key] || key;
87
+ }
88
+ class BagelAuth {
89
+ constructor(bagel) {
90
+ this.bagel = bagel;
91
+ __publicField(this, "user", null);
92
+ this.bagel = bagel;
93
+ }
94
+ async validateUser() {
95
+ try {
96
+ const usr = await this.bagel.get("/users/me");
97
+ this.user = usr;
98
+ return usr;
99
+ } catch (err) {
100
+ console.log(err);
101
+ return null;
102
+ }
103
+ }
104
+ async resetPassword(ctx) {
105
+ return this.bagel.post("auth/reset-password", ctx).catch((err) => {
106
+ throw responses(err.response?.data?.detail);
107
+ });
108
+ }
109
+ async forgotPassword(email) {
110
+ try {
111
+ await this.bagel.post("auth/forgot-password", { email });
112
+ } catch (err) {
113
+ throw responses(err?.response?.data?.detail);
114
+ }
115
+ }
116
+ async login(user) {
117
+ const formData = new FormData();
118
+ formData.append("username", user?.email || "");
119
+ formData.append("password", user?.password || "");
120
+ try {
121
+ await axios.post(`${this.bagel.host}/auth/cookie/login`, formData, {
122
+ headers: {
123
+ "Content-Type": "multipart/form-data",
124
+ "withCredentials": true
125
+ }
126
+ });
127
+ return this.validateUser();
128
+ } catch (err) {
129
+ throw responses(err.response?.data?.detail || "LOGIN_BAD_CREDENTIALS");
130
+ }
131
+ }
132
+ async logout() {
133
+ try {
134
+ await axios.post(`${this.bagel.host}/auth/cookie/logout`);
135
+ } catch (err) {
136
+ this.bagel.onError?.(err);
137
+ console.log(err);
138
+ }
139
+ this.user = null;
140
+ }
141
+ async acceptInvite(token, user) {
142
+ await axios.post(`${this.bagel.host}/auth/accept-invite/${token}`, user);
143
+ await this.login(user);
144
+ }
145
+ async register(user, errors) {
146
+ try {
147
+ await axios.post(`${this.bagel.host}/auth/register`, user);
148
+ this.login(user);
149
+ } catch (err) {
150
+ console.error(err);
151
+ errors.email = err.response.data.detail;
152
+ throw err;
153
+ }
154
+ }
155
+ }
156
+ class Bagel {
157
+ constructor({ host, onError }) {
158
+ __publicField(this, "host");
159
+ __publicField(this, "onError");
160
+ __publicField(this, "read_table", null);
161
+ __publicField(this, "auth", new BagelAuth(this));
162
+ this.host = host;
163
+ this.onError = onError;
164
+ }
165
+ data(table) {
166
+ return new DataRequest(table, this);
167
+ }
168
+ _endpointCleaner(endpoint) {
169
+ const url = `${endpoint.replace(/^\//, "").replace(/\/$/g, "")}`;
170
+ return url;
171
+ }
172
+ async api(endpoint, query) {
173
+ if (query) {
174
+ const queryParams = Object.entries(query).map(([key, value]) => `${key}=${value}`).join("&");
175
+ endpoint = `${endpoint}?${queryParams}`;
176
+ }
177
+ return axios.get(`${this.host}/api/${endpoint}`).then(({ data }) => data);
178
+ }
179
+ async get(endpoint, query) {
180
+ endpoint = this._endpointCleaner(endpoint);
181
+ if (endpoint.match(/undefined|null/))
182
+ throw new Error("Invalid endpoint");
183
+ if (query) {
184
+ const queryParams = Object.entries(query).filter(([_, value]) => !!value).map(([key, value]) => `${key}=${value}`).join("&");
185
+ if (queryParams)
186
+ endpoint = `${endpoint}?${queryParams}`;
187
+ }
188
+ const url = `${this.host}/${endpoint}`;
189
+ return axios.get(url).then(({ data }) => data).catch((err) => {
190
+ this.onError?.(err);
191
+ throw err;
192
+ });
193
+ }
194
+ async delete(endpoint) {
195
+ endpoint = this._endpointCleaner(endpoint);
196
+ return axios.delete(`${this.host}/${endpoint}`).then(({ data }) => data).catch((err) => {
197
+ this.onError?.(err);
198
+ throw err;
199
+ });
200
+ }
201
+ async put(endpoint, payload) {
202
+ endpoint = this._endpointCleaner(endpoint);
203
+ return axios.put(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
204
+ this.onError?.(err);
205
+ throw err;
206
+ });
207
+ }
208
+ async patch(endpoint, payload = {}) {
209
+ endpoint = this._endpointCleaner(endpoint);
210
+ return axios.patch(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
211
+ this.onError?.(err);
212
+ throw err;
213
+ });
214
+ }
215
+ async post(endpoint, payload = {}) {
216
+ endpoint = this._endpointCleaner(endpoint);
217
+ return axios.post(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
218
+ this.onError?.(err);
219
+ throw err;
220
+ });
221
+ }
222
+ async uploadFile(file, options) {
223
+ const formData = new FormData();
224
+ formData.append("file", file);
225
+ const { data } = await axios.post(`${this.host}/files/upload`, formData, {
226
+ headers: {
227
+ "Content-Type": "multipart/form-data"
228
+ },
229
+ onUploadProgress: options?.onUploadProgress
230
+ });
231
+ return data;
232
+ }
233
+ }
234
+
235
+ exports.Bagel = Bagel;
@@ -0,0 +1,61 @@
1
+ type Tables = '';
2
+ type TableToTypeMapping = Record<Tables, any>;
3
+ interface User {
4
+ id: string;
5
+ first_name?: string;
6
+ last_name?: string;
7
+ email?: string;
8
+ password?: string;
9
+ is_verified?: boolean;
10
+ locale: string;
11
+ type: string;
12
+ }
13
+ interface UploadOptions {
14
+ onUploadProgress?: (progressEvent: any) => void;
15
+ }
16
+ declare class DataRequest<T extends Tables = Tables> {
17
+ data_table: T | Tables;
18
+ bagel: any;
19
+ itemID: string;
20
+ _filter: Record<string, any>;
21
+ constructor(table: T, bagel: Bagel);
22
+ post(item: Record<string, any>): Promise<Record<string, any>>;
23
+ filter(filter: Record<string, any>): this;
24
+ get(): Promise<TableToTypeMapping[T] | TableToTypeMapping[T][] | undefined>;
25
+ item(id: string): this;
26
+ delete(): Promise<TableToTypeMapping[T][]>;
27
+ put(updatedItem: Record<string, any>): Promise<Record<string, any>>;
28
+ }
29
+ declare class BagelAuth {
30
+ private bagel;
31
+ constructor(bagel: Bagel);
32
+ user: User | null;
33
+ validateUser(): Promise<User | null>;
34
+ resetPassword(ctx: {
35
+ token: string;
36
+ password: string;
37
+ }): Promise<Record<string, any>>;
38
+ forgotPassword(email: string): Promise<void>;
39
+ login(user: User): Promise<User | null>;
40
+ logout(): Promise<void>;
41
+ acceptInvite(token: string, user: Record<string, any>): Promise<void>;
42
+ register(user: Record<string, any>, errors: Record<string, any>): Promise<void>;
43
+ }
44
+ declare class Bagel {
45
+ host: string;
46
+ onError?: (err: any) => void;
47
+ constructor({ host, onError }: Record<string, any>);
48
+ read_table: Tables | null;
49
+ data(table: Tables): DataRequest<Tables>;
50
+ auth: BagelAuth;
51
+ _endpointCleaner(endpoint: string): string;
52
+ api(endpoint: string, query?: Record<string, string>): Promise<Record<string, any>>;
53
+ get<T = Record<string, any>>(endpoint: string, query?: Record<string, any>): Promise<T>;
54
+ delete(endpoint: string): Promise<Record<string, any>>;
55
+ put(endpoint: string, payload: any): Promise<Record<string, any>>;
56
+ patch(endpoint: string, payload?: any): Promise<Record<string, any>>;
57
+ post(endpoint: string, payload?: any): Promise<Record<string, any>>;
58
+ uploadFile(file: File, options?: UploadOptions): Promise<any>;
59
+ }
60
+
61
+ export { Bagel, type TableToTypeMapping, type Tables, type User };
@@ -0,0 +1,61 @@
1
+ type Tables = '';
2
+ type TableToTypeMapping = Record<Tables, any>;
3
+ interface User {
4
+ id: string;
5
+ first_name?: string;
6
+ last_name?: string;
7
+ email?: string;
8
+ password?: string;
9
+ is_verified?: boolean;
10
+ locale: string;
11
+ type: string;
12
+ }
13
+ interface UploadOptions {
14
+ onUploadProgress?: (progressEvent: any) => void;
15
+ }
16
+ declare class DataRequest<T extends Tables = Tables> {
17
+ data_table: T | Tables;
18
+ bagel: any;
19
+ itemID: string;
20
+ _filter: Record<string, any>;
21
+ constructor(table: T, bagel: Bagel);
22
+ post(item: Record<string, any>): Promise<Record<string, any>>;
23
+ filter(filter: Record<string, any>): this;
24
+ get(): Promise<TableToTypeMapping[T] | TableToTypeMapping[T][] | undefined>;
25
+ item(id: string): this;
26
+ delete(): Promise<TableToTypeMapping[T][]>;
27
+ put(updatedItem: Record<string, any>): Promise<Record<string, any>>;
28
+ }
29
+ declare class BagelAuth {
30
+ private bagel;
31
+ constructor(bagel: Bagel);
32
+ user: User | null;
33
+ validateUser(): Promise<User | null>;
34
+ resetPassword(ctx: {
35
+ token: string;
36
+ password: string;
37
+ }): Promise<Record<string, any>>;
38
+ forgotPassword(email: string): Promise<void>;
39
+ login(user: User): Promise<User | null>;
40
+ logout(): Promise<void>;
41
+ acceptInvite(token: string, user: Record<string, any>): Promise<void>;
42
+ register(user: Record<string, any>, errors: Record<string, any>): Promise<void>;
43
+ }
44
+ declare class Bagel {
45
+ host: string;
46
+ onError?: (err: any) => void;
47
+ constructor({ host, onError }: Record<string, any>);
48
+ read_table: Tables | null;
49
+ data(table: Tables): DataRequest<Tables>;
50
+ auth: BagelAuth;
51
+ _endpointCleaner(endpoint: string): string;
52
+ api(endpoint: string, query?: Record<string, string>): Promise<Record<string, any>>;
53
+ get<T = Record<string, any>>(endpoint: string, query?: Record<string, any>): Promise<T>;
54
+ delete(endpoint: string): Promise<Record<string, any>>;
55
+ put(endpoint: string, payload: any): Promise<Record<string, any>>;
56
+ patch(endpoint: string, payload?: any): Promise<Record<string, any>>;
57
+ post(endpoint: string, payload?: any): Promise<Record<string, any>>;
58
+ uploadFile(file: File, options?: UploadOptions): Promise<any>;
59
+ }
60
+
61
+ export { Bagel, type TableToTypeMapping, type Tables, type User };
@@ -0,0 +1,61 @@
1
+ type Tables = '';
2
+ type TableToTypeMapping = Record<Tables, any>;
3
+ interface User {
4
+ id: string;
5
+ first_name?: string;
6
+ last_name?: string;
7
+ email?: string;
8
+ password?: string;
9
+ is_verified?: boolean;
10
+ locale: string;
11
+ type: string;
12
+ }
13
+ interface UploadOptions {
14
+ onUploadProgress?: (progressEvent: any) => void;
15
+ }
16
+ declare class DataRequest<T extends Tables = Tables> {
17
+ data_table: T | Tables;
18
+ bagel: any;
19
+ itemID: string;
20
+ _filter: Record<string, any>;
21
+ constructor(table: T, bagel: Bagel);
22
+ post(item: Record<string, any>): Promise<Record<string, any>>;
23
+ filter(filter: Record<string, any>): this;
24
+ get(): Promise<TableToTypeMapping[T] | TableToTypeMapping[T][] | undefined>;
25
+ item(id: string): this;
26
+ delete(): Promise<TableToTypeMapping[T][]>;
27
+ put(updatedItem: Record<string, any>): Promise<Record<string, any>>;
28
+ }
29
+ declare class BagelAuth {
30
+ private bagel;
31
+ constructor(bagel: Bagel);
32
+ user: User | null;
33
+ validateUser(): Promise<User | null>;
34
+ resetPassword(ctx: {
35
+ token: string;
36
+ password: string;
37
+ }): Promise<Record<string, any>>;
38
+ forgotPassword(email: string): Promise<void>;
39
+ login(user: User): Promise<User | null>;
40
+ logout(): Promise<void>;
41
+ acceptInvite(token: string, user: Record<string, any>): Promise<void>;
42
+ register(user: Record<string, any>, errors: Record<string, any>): Promise<void>;
43
+ }
44
+ declare class Bagel {
45
+ host: string;
46
+ onError?: (err: any) => void;
47
+ constructor({ host, onError }: Record<string, any>);
48
+ read_table: Tables | null;
49
+ data(table: Tables): DataRequest<Tables>;
50
+ auth: BagelAuth;
51
+ _endpointCleaner(endpoint: string): string;
52
+ api(endpoint: string, query?: Record<string, string>): Promise<Record<string, any>>;
53
+ get<T = Record<string, any>>(endpoint: string, query?: Record<string, any>): Promise<T>;
54
+ delete(endpoint: string): Promise<Record<string, any>>;
55
+ put(endpoint: string, payload: any): Promise<Record<string, any>>;
56
+ patch(endpoint: string, payload?: any): Promise<Record<string, any>>;
57
+ post(endpoint: string, payload?: any): Promise<Record<string, any>>;
58
+ uploadFile(file: File, options?: UploadOptions): Promise<any>;
59
+ }
60
+
61
+ export { Bagel, type TableToTypeMapping, type Tables, type User };
package/dist/index.mjs ADDED
@@ -0,0 +1,229 @@
1
+ import ax from 'axios';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => {
6
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ return value;
8
+ };
9
+ const axios = ax.create({
10
+ // withCredentials to true to send cookies with requests
11
+ withCredentials: true
12
+ });
13
+ class DataRequest {
14
+ constructor(table, bagel) {
15
+ __publicField(this, "data_table");
16
+ __publicField(this, "bagel");
17
+ __publicField(this, "itemID");
18
+ __publicField(this, "_filter", {});
19
+ this.data_table = table;
20
+ this.bagel = bagel;
21
+ this.itemID = "";
22
+ }
23
+ async post(item) {
24
+ if (!this.data_table)
25
+ throw new Error("Data table not set");
26
+ const { data } = await axios.post(
27
+ `${this.bagel.host}/data/${this.data_table}`,
28
+ item
29
+ );
30
+ return data;
31
+ }
32
+ filter(filter) {
33
+ this._filter = filter;
34
+ return this;
35
+ }
36
+ async get() {
37
+ if (!this.data_table)
38
+ throw new Error("Data table not set");
39
+ const filterStr = Object.keys(this._filter).length ? `?filter={${Object.entries(this._filter).map(([k, v]) => `${k}:${v}`).join(",")}}` : "";
40
+ const url = `${this.bagel.host}/data/${this.data_table}${this.itemID ? `/${this.itemID}` : ""}${filterStr}`;
41
+ try {
42
+ const { data } = await axios.get(url);
43
+ return data;
44
+ } catch (err) {
45
+ console.log(err);
46
+ this.bagel.onError?.(err);
47
+ return void 0;
48
+ }
49
+ }
50
+ item(id) {
51
+ this.itemID = id;
52
+ return this;
53
+ }
54
+ async delete() {
55
+ if (!this.data_table)
56
+ throw new Error("Data table not set");
57
+ const { data } = await axios.delete(
58
+ `${this.bagel.host}/data/${this.data_table}/${this.itemID}`
59
+ );
60
+ return data;
61
+ }
62
+ async put(updatedItem) {
63
+ const { data_table, itemID, bagel } = this;
64
+ if (!data_table)
65
+ throw new Error("Data table not set");
66
+ if (!itemID)
67
+ throw new Error("Item ID not set");
68
+ const { data } = await axios.put(
69
+ `${bagel.host}/data/${data_table}/${itemID}`,
70
+ updatedItem
71
+ );
72
+ return data;
73
+ }
74
+ }
75
+ function responses(key) {
76
+ const res = {
77
+ LOGIN_BAD_CREDENTIALS: "Invalid username or password",
78
+ RESET_PASSWORD_BAD_TOKEN: "This reset password link is invalid or expired."
79
+ };
80
+ return res[key] || key;
81
+ }
82
+ class BagelAuth {
83
+ constructor(bagel) {
84
+ this.bagel = bagel;
85
+ __publicField(this, "user", null);
86
+ this.bagel = bagel;
87
+ }
88
+ async validateUser() {
89
+ try {
90
+ const usr = await this.bagel.get("/users/me");
91
+ this.user = usr;
92
+ return usr;
93
+ } catch (err) {
94
+ console.log(err);
95
+ return null;
96
+ }
97
+ }
98
+ async resetPassword(ctx) {
99
+ return this.bagel.post("auth/reset-password", ctx).catch((err) => {
100
+ throw responses(err.response?.data?.detail);
101
+ });
102
+ }
103
+ async forgotPassword(email) {
104
+ try {
105
+ await this.bagel.post("auth/forgot-password", { email });
106
+ } catch (err) {
107
+ throw responses(err?.response?.data?.detail);
108
+ }
109
+ }
110
+ async login(user) {
111
+ const formData = new FormData();
112
+ formData.append("username", user?.email || "");
113
+ formData.append("password", user?.password || "");
114
+ try {
115
+ await axios.post(`${this.bagel.host}/auth/cookie/login`, formData, {
116
+ headers: {
117
+ "Content-Type": "multipart/form-data",
118
+ "withCredentials": true
119
+ }
120
+ });
121
+ return this.validateUser();
122
+ } catch (err) {
123
+ throw responses(err.response?.data?.detail || "LOGIN_BAD_CREDENTIALS");
124
+ }
125
+ }
126
+ async logout() {
127
+ try {
128
+ await axios.post(`${this.bagel.host}/auth/cookie/logout`);
129
+ } catch (err) {
130
+ this.bagel.onError?.(err);
131
+ console.log(err);
132
+ }
133
+ this.user = null;
134
+ }
135
+ async acceptInvite(token, user) {
136
+ await axios.post(`${this.bagel.host}/auth/accept-invite/${token}`, user);
137
+ await this.login(user);
138
+ }
139
+ async register(user, errors) {
140
+ try {
141
+ await axios.post(`${this.bagel.host}/auth/register`, user);
142
+ this.login(user);
143
+ } catch (err) {
144
+ console.error(err);
145
+ errors.email = err.response.data.detail;
146
+ throw err;
147
+ }
148
+ }
149
+ }
150
+ class Bagel {
151
+ constructor({ host, onError }) {
152
+ __publicField(this, "host");
153
+ __publicField(this, "onError");
154
+ __publicField(this, "read_table", null);
155
+ __publicField(this, "auth", new BagelAuth(this));
156
+ this.host = host;
157
+ this.onError = onError;
158
+ }
159
+ data(table) {
160
+ return new DataRequest(table, this);
161
+ }
162
+ _endpointCleaner(endpoint) {
163
+ const url = `${endpoint.replace(/^\//, "").replace(/\/$/g, "")}`;
164
+ return url;
165
+ }
166
+ async api(endpoint, query) {
167
+ if (query) {
168
+ const queryParams = Object.entries(query).map(([key, value]) => `${key}=${value}`).join("&");
169
+ endpoint = `${endpoint}?${queryParams}`;
170
+ }
171
+ return axios.get(`${this.host}/api/${endpoint}`).then(({ data }) => data);
172
+ }
173
+ async get(endpoint, query) {
174
+ endpoint = this._endpointCleaner(endpoint);
175
+ if (endpoint.match(/undefined|null/))
176
+ throw new Error("Invalid endpoint");
177
+ if (query) {
178
+ const queryParams = Object.entries(query).filter(([_, value]) => !!value).map(([key, value]) => `${key}=${value}`).join("&");
179
+ if (queryParams)
180
+ endpoint = `${endpoint}?${queryParams}`;
181
+ }
182
+ const url = `${this.host}/${endpoint}`;
183
+ return axios.get(url).then(({ data }) => data).catch((err) => {
184
+ this.onError?.(err);
185
+ throw err;
186
+ });
187
+ }
188
+ async delete(endpoint) {
189
+ endpoint = this._endpointCleaner(endpoint);
190
+ return axios.delete(`${this.host}/${endpoint}`).then(({ data }) => data).catch((err) => {
191
+ this.onError?.(err);
192
+ throw err;
193
+ });
194
+ }
195
+ async put(endpoint, payload) {
196
+ endpoint = this._endpointCleaner(endpoint);
197
+ return axios.put(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
198
+ this.onError?.(err);
199
+ throw err;
200
+ });
201
+ }
202
+ async patch(endpoint, payload = {}) {
203
+ endpoint = this._endpointCleaner(endpoint);
204
+ return axios.patch(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
205
+ this.onError?.(err);
206
+ throw err;
207
+ });
208
+ }
209
+ async post(endpoint, payload = {}) {
210
+ endpoint = this._endpointCleaner(endpoint);
211
+ return axios.post(`${this.host}/${endpoint}`, payload).then(({ data }) => data).catch((err) => {
212
+ this.onError?.(err);
213
+ throw err;
214
+ });
215
+ }
216
+ async uploadFile(file, options) {
217
+ const formData = new FormData();
218
+ formData.append("file", file);
219
+ const { data } = await axios.post(`${this.host}/files/upload`, formData, {
220
+ headers: {
221
+ "Content-Type": "multipart/form-data"
222
+ },
223
+ onUploadProgress: options?.onUploadProgress
224
+ });
225
+ return data;
226
+ }
227
+ }
228
+
229
+ export { Bagel };
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@bagelink/sdk",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "Bagel core sdk packages",
6
+ "author": {
7
+ "name": "Neveh Allon",
8
+ "email": "neveh@bagelstudio.co.il",
9
+ "url": "https://github.com/nevehallon"
10
+ },
11
+ "license": "MIT",
12
+ "homepage": "https://github.com/bageldb/bagelink/tree/master/packages/sdk#readme",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/bageldb/bagelink.git",
16
+ "directory": "packages/sdk"
17
+ },
18
+ "bugs": "https://github.com/bageldb/bagelink/issues",
19
+ "keywords": [],
20
+ "sideEffects": false,
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "require": "./dist/index.cjs",
25
+ "import": "./dist/index.mjs"
26
+ }
27
+ },
28
+ "main": "./dist/index.mjs",
29
+ "module": "./dist/index.mjs",
30
+ "types": "./dist/index.d.ts",
31
+ "typesVersions": {
32
+ "*": {
33
+ "*": [
34
+ "./dist/*",
35
+ "./dist/index.d.ts"
36
+ ]
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "axios": "^1.6.1"
47
+ },
48
+ "scripts": {
49
+ "dev": "unbuild --stub",
50
+ "build": "unbuild",
51
+ "start": "tsx src/index.ts",
52
+ "watch": "tsx watch src/index.ts"
53
+ }
54
+ }