@bagelink/sdk 0.0.466 → 0.0.473

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/src/index.ts CHANGED
@@ -1,101 +1,101 @@
1
- import ax from 'axios';
1
+ import ax from 'axios'
2
2
 
3
- import openAPI from './openAPITools';
3
+ import openAPI from './openAPITools'
4
4
 
5
- export type Tables = '';
6
- export type TableToTypeMapping = Record<Tables, any>;
5
+ export type Tables = ''
6
+ export type TableToTypeMapping = Record<Tables, any>
7
7
 
8
- export { openAPI };
8
+ export { openAPI }
9
9
  export interface User {
10
- id: string;
11
- first_name?: string;
12
- last_name?: string;
13
- email?: string;
14
- password?: string;
15
- is_verified?: boolean;
16
- locale: string;
17
- type: string;
10
+ id: string
11
+ first_name?: string
12
+ last_name?: string
13
+ email?: string
14
+ password?: string
15
+ is_verified?: boolean
16
+ locale: string
17
+ type: string
18
18
  }
19
19
 
20
20
  interface UploadOptions {
21
- // eslint-disable-next-line no-unused-vars
22
- onUploadProgress?: (progressEvent: any) => void;
21
+
22
+ onUploadProgress?: (progressEvent: any) => void
23
23
  }
24
24
 
25
25
  const axios = ax.create({
26
26
  withCredentials: true,
27
- });
27
+ })
28
28
 
29
29
  class DataRequest<T extends Tables = Tables> {
30
- data_table: T | Tables;
30
+ data_table: T | Tables
31
31
 
32
- bagel: any;
32
+ bagel: any
33
33
 
34
- itemID: string;
34
+ itemID: string
35
35
 
36
- _filter: Record<string, any> = {};
36
+ _filter: Record<string, any> = {}
37
37
 
38
38
  constructor(table: T, bagel: Bagel) {
39
- this.data_table = table;
40
- this.bagel = bagel;
41
- this.itemID = '';
39
+ this.data_table = table
40
+ this.bagel = bagel
41
+ this.itemID = ''
42
42
  }
43
43
 
44
44
  async post(item: Record<string, any>): Promise<Record<string, any>> {
45
- if (!this.data_table) throw new Error('Data table not set');
46
- const { data } = await axios.post(`/data/${this.data_table}`, item);
47
- return data;
45
+ if (!this.data_table) throw new Error('Data table not set')
46
+ const { data } = await axios.post(`/data/${this.data_table}`, item)
47
+ return data
48
48
  }
49
49
 
50
50
  filter(filter: Record<string, any>) {
51
- this._filter = filter;
52
- return this;
51
+ this._filter = filter
52
+ return this
53
53
  }
54
54
 
55
55
  async get(): Promise<
56
56
  TableToTypeMapping[T] | TableToTypeMapping[T][] | undefined
57
- > {
58
- if (!this.data_table) throw new Error('Data table not set');
57
+ > {
58
+ if (!this.data_table) throw new Error('Data table not set')
59
59
  const filterStr = Object.keys(this._filter).length
60
60
  ? `?filter={${Object.entries(this._filter)
61
61
  .map(([k, v]) => `${k}:${v}`)
62
62
  .join(',')}}`
63
- : '';
63
+ : ''
64
64
  const url = `/data/${this.data_table}${
65
65
  this.itemID ? `/${this.itemID}` : ''
66
- }${filterStr}`;
66
+ }${filterStr}`
67
67
  try {
68
- const { data } = await axios.get(url);
69
- return data;
68
+ const { data } = await axios.get(url)
69
+ return data
70
70
  } catch (err) {
71
- console.log(err);
72
- this.bagel.onError?.(err);
73
- return undefined;
71
+ console.log(err)
72
+ this.bagel.onError?.(err)
73
+ return undefined
74
74
  }
75
75
  }
76
76
 
77
77
  item(id: string) {
78
- this.itemID = id;
79
- return this;
78
+ this.itemID = id
79
+ return this
80
80
  }
81
81
 
82
82
  async delete(): Promise<TableToTypeMapping[T][]> {
83
- if (!this.data_table) throw new Error('Data table not set');
83
+ if (!this.data_table) throw new Error('Data table not set')
84
84
  const { data } = await axios.delete(
85
85
  `/data/${this.data_table}/${this.itemID}`,
86
- );
87
- return data;
86
+ )
87
+ return data
88
88
  }
89
89
 
90
90
  async put(updatedItem: Record<string, any>): Promise<Record<string, any>> {
91
- const { data_table, itemID } = this;
92
- if (!data_table) throw new Error('Data table not set');
93
- if (!itemID) throw new Error('Item ID not set');
91
+ const { data_table, itemID } = this
92
+ if (!data_table) throw new Error('Data table not set')
93
+ if (!itemID) throw new Error('Item ID not set')
94
94
  const { data } = await axios.put(
95
95
  `/data/${data_table}/${itemID}`,
96
96
  updatedItem,
97
- );
98
- return data;
97
+ )
98
+ return data
99
99
  }
100
100
  }
101
101
 
@@ -103,118 +103,117 @@ function responses(key: string) {
103
103
  const res: Record<string, string> = {
104
104
  LOGIN_BAD_CREDENTIALS: 'Invalid username or password',
105
105
  RESET_PASSWORD_BAD_TOKEN: 'This reset password link is invalid or expired.',
106
- };
107
- return res[key] || key;
106
+ }
107
+ return res[key] || key
108
108
  }
109
109
 
110
110
  class BagelAuth {
111
111
  constructor(private bagel: Bagel) {
112
- this.bagel = bagel;
112
+ this.bagel = bagel
113
113
  }
114
114
 
115
- user: User | null = null;
115
+ user: User | null = null
116
116
 
117
117
  async validateUser(): Promise<User | null> {
118
118
  try {
119
119
  const { data: usr } = await axios.get('/users/me', {
120
120
  withCredentials: true,
121
- });
122
- this.user = usr;
123
- return usr;
121
+ })
122
+ this.user = usr
123
+ return usr
124
124
  } catch (err) {
125
- return null;
125
+ return null
126
126
  }
127
127
  }
128
128
 
129
- async resetPassword(ctx: { token: string; password: string }) {
129
+ async resetPassword(ctx: { token: string, password: string }) {
130
130
  return this.bagel.post('auth/reset-password', ctx).catch((err) => {
131
- throw responses(err.response?.data?.detail);
132
- });
131
+ throw responses(err.response?.data?.detail)
132
+ })
133
133
  }
134
134
 
135
135
  async forgotPassword(email: string) {
136
136
  try {
137
- await this.bagel.post('auth/forgot-password', { email });
137
+ await this.bagel.post('auth/forgot-password', { email })
138
138
  } catch (err: any) {
139
- throw responses(err?.response?.data?.detail);
139
+ throw responses(err?.response?.data?.detail)
140
140
  }
141
141
  }
142
142
 
143
143
  async login(user: User): Promise<User | null> {
144
- const formData = new FormData();
145
- formData.append('username', user?.email || '');
146
- formData.append('password', user?.password || '');
147
- console.log('Logging in');
144
+ const formData = new FormData()
145
+ formData.append('username', user.email || '')
146
+ formData.append('password', user.password || '')
147
+ console.log('Logging in')
148
148
  try {
149
149
  await axios.post('/auth/cookie/login', formData, {
150
150
  headers: {
151
- withCredentials: true,
151
+ 'withCredentials': true,
152
152
  'Content-Type': 'multipart/form-data',
153
153
  },
154
- });
155
- axios.defaults.withCredentials = true;
156
- return this.validateUser();
154
+ })
155
+ axios.defaults.withCredentials = true
156
+ return this.validateUser()
157
157
  } catch (err: any) {
158
- throw responses(err.response?.data?.detail || 'LOGIN_BAD_CREDENTIALS');
158
+ throw responses(err.response?.data?.detail || 'LOGIN_BAD_CREDENTIALS')
159
159
  }
160
160
  }
161
161
 
162
162
  async logout() {
163
163
  try {
164
- await axios.post('/auth/cookie/logout');
164
+ await axios.post('/auth/cookie/logout')
165
165
  } catch (err) {
166
- this.bagel.onError?.(err);
167
- console.log(err);
166
+ this.bagel.onError?.(err)
167
+ console.log(err)
168
168
  }
169
- this.user = null;
169
+ this.user = null
170
170
  }
171
171
 
172
172
  async acceptInvite(token: string, user: Record<string, any>) {
173
- await axios.post(`/auth/accept-invite/${token}`, user);
174
- await this.login(user as User);
173
+ await axios.post(`/auth/accept-invite/${token}`, user)
174
+ await this.login(user as User)
175
175
  }
176
176
 
177
177
  async register(user: Record<string, any>, errors: Record<string, any>) {
178
178
  try {
179
- await axios.post<User>('/auth/register', user);
180
- return this.login(user as User);
179
+ await axios.post<User>('/auth/register', user)
180
+ return this.login(user as User)
181
181
  } catch (err: any) {
182
- console.error(err);
182
+ console.error(err)
183
183
 
184
- errors.email = err.response.data.detail;
184
+ errors.email = err.response.data.detail
185
185
 
186
- throw err;
186
+ throw err
187
187
  }
188
188
  }
189
189
  }
190
190
  export class Bagel {
191
- host?: string;
191
+ host?: string
192
192
 
193
- // eslint-disable-next-line no-unused-vars
194
- onError?: (err: any) => void;
193
+ onError?: (err: any) => void
195
194
 
196
195
  constructor({ host, onError }: Record<string, any>) {
197
- this.host = host?.replace(/\/$/, '');
196
+ this.host = host?.replace(/\/$/, '')
198
197
  if (!this.host) {
199
198
  throw new Error(
200
199
  'you probably need to set VITE_BAGEL_BASE_URL in the .env file',
201
- );
200
+ )
202
201
  }
203
- axios.defaults.baseURL = this.host;
204
- this.onError = onError;
202
+ axios.defaults.baseURL = this.host
203
+ this.onError = onError
205
204
  }
206
205
 
207
- read_table: Tables | null = null;
206
+ read_table: Tables | null = null
208
207
 
209
208
  data(table: Tables): DataRequest<Tables> {
210
- return new DataRequest(table, this);
209
+ return new DataRequest(table, this)
211
210
  }
212
211
 
213
- auth = new BagelAuth(this);
212
+ auth = new BagelAuth(this)
214
213
 
215
214
  _endpointCleaner(endpoint: string) {
216
- const url = `${endpoint.replace(/^\//, '').replace(/\/$/g, '')}`;
217
- return url;
215
+ const url = `${endpoint.replace(/^\//, '').replace(/\/$/g, '')}`
216
+ return url
218
217
  }
219
218
 
220
219
  async api(
@@ -224,81 +223,81 @@ export class Bagel {
224
223
  if (query) {
225
224
  const queryParams = Object.entries(query)
226
225
  .map(([key, value]) => `${key}=${value}`)
227
- .join('&');
228
- endpoint = `${endpoint}?${queryParams}`;
226
+ .join('&')
227
+ endpoint = `${endpoint}?${queryParams}`
229
228
  }
230
229
  return axios
231
230
  .get(`/api/${endpoint}`)
232
- .then(({ data }: { data: any }) => data);
231
+ .then(({ data }: { data: any }) => data)
233
232
  }
234
233
 
235
234
  async get<T = Record<string, any>>(
236
235
  endpoint: string,
237
236
  query?: Record<string, any>,
238
237
  ): Promise<T> {
239
- this._setAuthorization();
240
- endpoint = this._endpointCleaner(endpoint);
241
- if (endpoint.match(/undefined|null/)) throw new Error('Invalid endpoint');
238
+ this._setAuthorization()
239
+ endpoint = this._endpointCleaner(endpoint)
240
+ if (endpoint.match(/undefined|null/)) throw new Error('Invalid endpoint')
242
241
  if (query) {
243
242
  const queryParams = Object.entries(query)
244
- // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
243
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
245
244
  .filter(([_, value]) => !!value)
246
245
  .map(([key, value]) => `${key}=${value}`)
247
- .join('&');
248
- if (queryParams) endpoint = `${endpoint}?${queryParams}`;
246
+ .join('&')
247
+ if (queryParams) endpoint = `${endpoint}?${queryParams}`
249
248
  }
250
- const url = `/${endpoint}`;
249
+ const url = `/${endpoint}`
251
250
  return axios
252
251
  .get(url)
253
252
  .then(({ data }: { data: any }) => data)
254
253
  .catch((err: any) => {
255
- this.onError?.(err);
256
- throw err;
257
- });
254
+ this.onError?.(err)
255
+ throw err
256
+ })
258
257
  }
259
258
 
260
259
  async delete(endpoint: string): Promise<Record<string, any>> {
261
- this._setAuthorization();
262
- endpoint = this._endpointCleaner(endpoint);
260
+ this._setAuthorization()
261
+ endpoint = this._endpointCleaner(endpoint)
263
262
  return axios
264
263
  .delete(`/${endpoint}`)
265
264
  .then(({ data }: { data: any }) => data)
266
265
  .catch((err: any) => {
267
- this.onError?.(err);
268
- throw err;
269
- });
266
+ this.onError?.(err)
267
+ throw err
268
+ })
270
269
  }
271
270
 
272
271
  async put(endpoint: string, payload: any): Promise<Record<string, any>> {
273
- endpoint = this._endpointCleaner(endpoint);
274
- this._setAuthorization();
272
+ endpoint = this._endpointCleaner(endpoint)
273
+ this._setAuthorization()
275
274
  return axios
276
275
  .put(`/${endpoint}`, payload)
277
276
  .then(({ data }: { data: any }) => data)
278
277
  .catch((err: any) => {
279
- this.onError?.(err);
280
- throw err;
281
- });
278
+ this.onError?.(err)
279
+ throw err
280
+ })
282
281
  }
283
282
 
284
283
  async patch(
285
284
  endpoint: string,
286
285
  payload: any = {},
287
286
  ): Promise<Record<string, any>> {
288
- endpoint = this._endpointCleaner(endpoint);
287
+ endpoint = this._endpointCleaner(endpoint)
289
288
  return axios
290
289
  .patch(`/${endpoint}`, payload)
291
290
  .then(({ data }: { data: any }) => data)
292
291
  .catch((err: any) => {
293
- this.onError?.(err);
294
- throw err;
295
- });
292
+ this.onError?.(err)
293
+ throw err
294
+ })
296
295
  }
297
296
 
298
297
  _setAuthorization() {
299
- const Authorization = localStorage.getItem('access_token');
298
+ const Authorization = localStorage.getItem('access_token')
300
299
  if (Authorization) {
301
- axios.defaults.headers.common.Authorization = `Bearer ${Authorization}`;
300
+ axios.defaults.headers.common.Authorization = `Bearer ${Authorization}`
302
301
  }
303
302
  }
304
303
 
@@ -306,21 +305,21 @@ export class Bagel {
306
305
  endpoint: string,
307
306
  payload: any = {},
308
307
  ): Promise<Record<string, any>> {
309
- this._setAuthorization();
310
- endpoint = this._endpointCleaner(endpoint);
308
+ this._setAuthorization()
309
+ endpoint = this._endpointCleaner(endpoint)
311
310
  return axios
312
311
  .post(`/${endpoint}`, payload)
313
312
  .then(({ data }: { data: any }) => data)
314
313
  .catch((err: any) => {
315
- this.onError?.(err);
316
- throw err;
317
- });
314
+ this.onError?.(err)
315
+ throw err
316
+ })
318
317
  }
319
318
 
320
319
  async uploadFile<T = any>(file: File, options?: UploadOptions): Promise<T> {
321
- this._setAuthorization();
322
- const formData = new FormData();
323
- formData.append('file', file);
320
+ this._setAuthorization()
321
+ const formData = new FormData()
322
+ formData.append('file', file)
324
323
  // get an indication of the progress
325
324
 
326
325
  const { data } = await axios.post<T>('/static_files/upload', formData, {
@@ -328,7 +327,7 @@ export class Bagel {
328
327
  'Content-Type': 'multipart/form-data',
329
328
  },
330
329
  onUploadProgress: options?.onUploadProgress,
331
- });
332
- return data;
330
+ })
331
+ return data
333
332
  }
334
333
  }