Page MenuHomeSealhub

collection.ts
No OneTemporary

Authored By
Unknown
Size
4 KB
Referenced Files
None
Subscribers
None

collection.ts

import { useState, useEffect } from "./react-api/api";
import axios from "axios";
import EventEmitter from "eventemitter3";
import {
SealiousItem,
SealiousCollectionResponse,
CollectionParams,
ComplexFilterParam,
} from "./types";
import { CollectionItem } from "./item";
import url from "./url";
const DEFAULT_ITEMS_PER_PAGE = 10;
export function useCollection<
ItemFields,
ItemClass extends CollectionItem<ItemFields>,
TCollection extends CollectionClient<ItemFields, ItemClass>
>(
CollectionClass: CollectionClass<ItemFields, ItemClass, TCollection>,
params: CollectionParams<ItemFields>
): [TCollection, ItemClass[], CollectionParams<ItemFields>] {
const [collectionClient] = useState<TCollection>(
() => new CollectionClass(params)
);
const [items, setItems] = useState<ItemClass[]>([]);
useEffect(() => {
const callback = () =>
collectionClient
.refresh()
.then(() => setItems(collectionClient.items));
collectionClient.on("change", callback);
callback();
return () => {
collectionClient.removeListener("change", callback);
};
}, []);
return [collectionClient, items, collectionClient.params];
}
export type CollectionClass<
ItemFields,
Y extends CollectionItem<ItemFields>,
TCollection extends CollectionClient<ItemFields, Y>
> = new (params: CollectionParams<ItemFields>) => TCollection;
export default class CollectionClient<
ItemFields,
ItemClass extends CollectionItem<ItemFields>
> extends EventEmitter {
items: ItemClass[];
collection_name: string;
item_constructor: new (
id: string,
body: ItemFields & SealiousItem,
attachments?: { [id: string]: SealiousItem }
) => ItemClass;
params: CollectionParams<ItemFields>;
needs_saving: boolean = false;
has_next_page: boolean | null = null;
constructor(params: CollectionParams<ItemFields>) {
super();
this.params = params;
this.save = this.save.bind(this);
this.setPage = this.setPage.bind(this);
this.getPage = this.getPage.bind(this);
this.nextPage = this.nextPage.bind(this);
this.prevPage = this.prevPage.bind(this);
}
setFilter<Field extends keyof ItemFields>(
field_name: Field,
value: ComplexFilterParam<ItemFields[Field]> | ItemFields[Field],
replace: boolean = false
) {
if (!this.params.filter) {
this.params.filter = {};
}
if (replace) {
this.params.filter[field_name] = value;
} else {
if (typeof value == "object") {
this.params.filter[field_name] = {
...this.params.filter[field_name],
...value,
};
} else {
this.params.filter = {
...this.params.filter,
[field_name]: value,
};
}
}
this.emit("change");
}
isPaginated(): boolean {
return typeof this.params.pagination == "object";
}
setPage(page: number) {
if (!this.isPaginated()) {
throw new Error("This client does not use pagination");
}
this.params.pagination = {
items: this?.params?.pagination?.items || DEFAULT_ITEMS_PER_PAGE,
page: page,
};
this.emit("change");
}
getPage(): number {
if (!this.isPaginated()) {
throw new Error("This client does not use pagination");
}
return this.params?.pagination?.page || 1;
}
nextPage() {
if (this.has_next_page) {
this.setPage(this.getPage() + 1);
}
}
prevPage() {
if (this.getPage() > 0) {
this.setPage(this.getPage() - 1);
}
}
async refresh(): Promise<void> {
const response = (await axios.get(
url(`/api/v1/collections/${this.collection_name}`, this.params)
)) as { data: SealiousCollectionResponse<SealiousItem & ItemFields> };
this.needs_saving = false;
const attachments = response.data.attachments;
if (this.isPaginated()) {
this.has_next_page =
response.data.items.length === this.params?.pagination?.items;
}
this.items = response.data.items.map((item) => {
const entry = new this.item_constructor(item.id, item, attachments);
entry.on("change", () => this.emit("change"));
entry.on("temp-change", () => (this.needs_saving = true));
return entry;
});
}
async create(body: ItemFields) {
const response = await axios.post(
`/api/v1/collections/${this.collection_name}`,
body
);
this.emit("change");
return response.data.items;
}
async save() {
const promises = [];
for (const item of this.items) {
if (item.needs_saving) {
promises.push(item.save());
}
}
await Promise.all(promises);
this.needs_saving = false;
this.emit("change");
}
}

File Metadata

Mime Type
application/javascript
Expires
Fri, Nov 27, 20:00 (6 h, 59 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1229539
Default Alt Text
collection.ts (4 KB)

Event Timeline