Page MenuHomeSealhub

sealious-list.ts
No OneTemporary

sealious-list.ts

import { Context } from "koa";
import { BaseListPageFields, ListPage } from "./list.js";
import {
Collection,
CollectionItem,
ItemList,
Context as SealiousContext,
CollectionInput,
} from "sealious";
import { FlatTemplatable } from "tempstream";
import { peopleWhoCan } from "./access-control.js";
import qs from "qs";
import { is, predicates } from "@sealcode/ts-predicates";
export abstract class SealiousItemListPage<
C extends Collection,
F extends typeof BaseListPageFields
> extends ListPage<CollectionItem<C>, F> {
constructor(public collection: C) {
super();
}
async getContextForList(ctx: Context): Promise<SealiousContext> {
return ctx.$context;
}
async getTotalPages(ctx: Context, itemsPerPage: number): Promise<number> {
const query = this.collection.list(await this.getContextForList(ctx));
await this.addFilter(ctx, query);
const { items } = await query.fetch();
return Math.ceil(items.length / itemsPerPage);
}
protected async addFilter(ctx: Context, list: ItemList<C>): Promise<void> {
const filters = await this.getFilterValues(ctx);
for (const key in filters) {
if (filters[key] === undefined || filters[key] == "") {
delete filters[key];
}
}
if (Object.keys(filters).length) {
list.filter(filters as Partial<CollectionInput<C>>);
}
}
async makeQuery(ctx: Context): Promise<ItemList<C>> {
const query = this.collection.list(await this.getContextForList(ctx));
const sort = await this.getSort(ctx);
if (sort) {
query.sort({ [sort.field]: sort.order } as any);
}
return query;
}
async getItems(
ctx: Context,
page: number,
itemsPerPage: number
): Promise<CollectionItem<C>[]> {
const query = await this.makeQuery(ctx);
await this.addFilter(ctx, query);
const { items } = await query
.paginate({ items: itemsPerPage, page })
.fetch();
return items;
}
async getFilterValues(ctx: Context) {
const query_params = qs.parse(ctx.search.slice(1));
const _filter_values = query_params?.filter || {};
let filter_values: Record<string, string | undefined> = is(
_filter_values,
predicates.record(predicates.string, predicates.string)
)
? _filter_values
: {};
return filter_values;
}
async renderItem(
_: Context,
item: CollectionItem<C>,
index: number
): Promise<FlatTemplatable> {
return `<div>${item.id}</div>`;
}
canAccess = peopleWhoCan("list", this.collection);
}

File Metadata

Mime Type
text/x-java
Expires
Fri, Jan 24, 16:50 (1 h, 2 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
601376
Default Alt Text
sealious-list.ts (2 KB)

Event Timeline