diff --git a/src/lib/database.ts b/src/lib/database.ts index 9e0a77b..184a7ff 100644 --- a/src/lib/database.ts +++ b/src/lib/database.ts @@ -138,7 +138,17 @@ class Collection { } class Document { - constructor(protected databaseId: string, protected collectionId: string, protected documentId: string) { } + protected databaseId: string + protected collectionId: string + protected documentId: string + + constructor(databaseId: string, collectionId: string, documentId: string) + constructor(document: Models.Document) + constructor(databaseId: string | Models.Document, collectionId?: string, documentId?: string) { + this.databaseId = typeof databaseId === 'string' ? databaseId : databaseId.$database + this.collectionId = typeof databaseId === 'string' ? collectionId : databaseId.$collection + this.documentId = typeof databaseId === 'string' ? documentId : databaseId.$id + } createSubscriber() { const dataStore = writable(null) @@ -173,6 +183,11 @@ class Document { return databases.updateDocument(this.databaseId, this.collectionId, this.documentId, data, permissions) } + + static async create(databaseId: string, collectionId: string, data: { [key: string]: any } = {}, permissions: string[] = []) { + const created = await databases.createDocument(databaseId, collectionId, ID.unique(), data, permissions) + return new Document(created) + } } export { Collection, Document } diff --git a/src/lib/storage.ts b/src/lib/storage.ts index 65d81e3..52237b1 100644 --- a/src/lib/storage.ts +++ b/src/lib/storage.ts @@ -130,7 +130,15 @@ class Bucket { } class File { - constructor(protected bucketId: string, protected fileId: string) { } + protected bucketId: string + protected fileId: string + + constructor(bucketId: string, fileId: string) + constructor(file: Models.File) + constructor(bucketId: string | Models.File, fileId?: string) { + this.bucketId = typeof bucketId === 'string' ? bucketId : bucketId.bucketId + this.fileId = typeof bucketId === 'string' ? fileId : bucketId.$id + } createSubscriber() { const fileStore = writable(null) @@ -177,9 +185,22 @@ class File { } async getContent() { - const { href } = await storage.getFileView(this.bucketId, this.fileId) + const fileContent = writable('') + const loading = writable(true) - return await fetch(href) + const { href } = storage.getFileView(this.bucketId, this.fileId) + + fetch(href).then(res => res.ok ? res.text() : null).then(res => { + fileContent.set(res ?? '') + loading.set(false) + }) + + return [{ subscribe: fileContent.subscribe }, { subscribe: loading.subscribe }] as const + } + + static async create(bucketId: string, file, permissions: string[] = []) { + const created = await storage.createFile(bucketId, ID.unique(), file, permissions) + return new File(created) } }