Skip to content

Instantly share code, notes, and snippets.

@alexweininger
Created August 15, 2021 04:21
Show Gist options
  • Save alexweininger/ed363ce6d312367252f0718db6f7dbc2 to your computer and use it in GitHub Desktop.
Save alexweininger/ed363ce6d312367252f0718db6f7dbc2 to your computer and use it in GitHub Desktop.
Appwrite database collection client
import { Appwrite } from 'appwrite';
export type Document<T = any> = T & {
$id: string;
$collection: string;
$permissions: any;
};
export type DocumentsList<T = any> = {
sum: number;
documents: Document<T>[];
};
export class CollectionClient<T> {
private readonly db;
constructor(private readonly id: string, appwrite: Appwrite, private readonly idProp: (keyof T)[]) {
this.db = appwrite.database;
}
public async add(data: T) {
const list = await this.get();
const alreadyExists = list.documents.some((doc) => {
const isEqual = this.isEqual(data, doc);
console.log(isEqual, data, doc);
return isEqual;
});
if (alreadyExists) {
throw new Error('Unable to add document, document already exists.');
}
await this.db.createDocument(this.id, data as Record<string, unknown>);
}
public async delete(id: string): Promise<void> {
await this.db.deleteDocument(this.id, id);
}
public async update(id: string, data: Partial<T>): Promise<void> {
await this.db.updateDocument(this.id, id, data);
}
public async get(): Promise<DocumentsList<T>> {
return this.db.listDocuments(this.id);
}
public async getById(id: string): Promise<Document<T>> {
return this.db.getDocument(this.id, id);
}
public isEqual(a: T, b: T) {
return this.idProp.every((prop) => a[prop] === b[prop]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment