|
| 1 | +import type { KyInstance } from 'ky' |
| 2 | +import type { AuthService } from './auth.service' |
| 3 | + |
| 4 | +interface IRecord { |
| 5 | + id: string |
| 6 | + values: Record<string, unknown> |
| 7 | +} |
| 8 | + |
| 9 | +interface CreateRecordPayload { |
| 10 | + values: Record<string, unknown> |
| 11 | +} |
| 12 | + |
| 13 | +interface UpdateRecordPayload { |
| 14 | + values: Record<string, unknown> |
| 15 | +} |
| 16 | + |
| 17 | +export class TableService { |
| 18 | + private client: KyInstance |
| 19 | + private baseName: string |
| 20 | + private tableName: string |
| 21 | + private viewName?: string |
| 22 | + private authService: AuthService |
| 23 | + |
| 24 | + constructor(client: KyInstance, baseName: string, tableName: string, authService: AuthService, viewName?: string) { |
| 25 | + this.client = client |
| 26 | + this.baseName = baseName |
| 27 | + this.tableName = tableName |
| 28 | + this.viewName = viewName |
| 29 | + this.authService = authService |
| 30 | + } |
| 31 | + |
| 32 | + private checkAuth() { |
| 33 | + if (!this.authService.isAuthenticated()) { |
| 34 | + throw new Error('Authentication is missing. Please login first.') |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private getUrl(path: string): string { |
| 39 | + if (this.viewName) { |
| 40 | + return `bases/${this.baseName}/tables/${this.tableName}/views/${this.viewName}/${path}` |
| 41 | + } |
| 42 | + return `bases/${this.baseName}/tables/${this.tableName}/${path}` |
| 43 | + } |
| 44 | + |
| 45 | + async getRecords(): Promise<IRecord[]> { |
| 46 | + this.checkAuth() |
| 47 | + const response = await this.client.get(this.getUrl('records')).json<{ records: IRecord[] }>() |
| 48 | + return response.records |
| 49 | + } |
| 50 | + |
| 51 | + async createRecord(payload: CreateRecordPayload): Promise<IRecord> { |
| 52 | + this.checkAuth() |
| 53 | + const response = await this.client.post(this.getUrl('records'), { json: payload }).json<IRecord>() |
| 54 | + return response |
| 55 | + } |
| 56 | + |
| 57 | + async updateRecord(recordId: string, payload: UpdateRecordPayload): Promise<IRecord> { |
| 58 | + this.checkAuth() |
| 59 | + const response = await this.client.patch(this.getUrl(`records/${recordId}`), { json: payload }).json<IRecord>() |
| 60 | + return response |
| 61 | + } |
| 62 | + |
| 63 | + async deleteRecord(recordId: string): Promise<void> { |
| 64 | + this.checkAuth() |
| 65 | + await this.client.delete(this.getUrl(`records/${recordId}`)) |
| 66 | + } |
| 67 | +} |
0 commit comments