Something went wrong. Try again.
A social knowledge tool for research trails, built on ATProto semble.so
research-tool social-network tools-for-thought atproto
Something went wrong. Try again.
TypeScript
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629import { ICollectionQueryRepository, CollectionQueryOptions, CollectionQueryResultDTO, CollectionContainingCardDTO, CollectionForUrlRawDTO, PaginatedQueryResult, CollectionSortField, SortOrder, CollectionForUrlQueryOptions, SearchCollectionsOptions, GetOpenCollectionsWithContributorOptions, CollectionContributorDTO, CollectionWithMatchedUrlsDTO,} from '../../domain/ICollectionQueryRepository';import { Collection } from '../../domain/Collection';import { InMemoryCollectionRepository } from './InMemoryCollectionRepository';import { InMemoryCardRepository } from './InMemoryCardRepository';
export class InMemoryCollectionQueryRepository implements ICollectionQueryRepository { constructor( private collectionRepository: InMemoryCollectionRepository, private cardRepository?: InMemoryCardRepository, ) {}
async findByCreator( curatorId: string, options: CollectionQueryOptions, ): Promise<PaginatedQueryResult<CollectionQueryResultDTO>> { try { const allCollections = this.collectionRepository.getAllCollections(); let creatorCollections = allCollections.filter( (collection) => collection.authorId.value === curatorId, );
if (options.searchText && options.searchText.trim()) { const searchTerm = options.searchText.trim().toLowerCase(); creatorCollections = creatorCollections.filter((collection) => { const nameMatch = collection.name.value .toLowerCase() .includes(searchTerm); const descriptionMatch = collection.description?.value.toLowerCase().includes(searchTerm) || false; return nameMatch || descriptionMatch; }); }
const sortedCollections = this.sortCollections( creatorCollections, options.sortBy, options.sortOrder, );
const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedCollections = sortedCollections.slice( startIndex, endIndex, );
const items: CollectionQueryResultDTO[] = paginatedCollections.map( (collection) => { const collectionPublishedRecordId = collection.publishedRecordId; return { id: collection.collectionId.getStringValue(), uri: collectionPublishedRecordId?.uri, authorId: collection.authorId.value, name: collection.name.value, description: collection.description?.value, accessType: collection.accessType, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, }; }, );
return { items, totalCount: creatorCollections.length, hasMore: endIndex < creatorCollections.length, }; } catch (error) { throw new Error( `Failed to query collections: ${error instanceof Error ? error.message : String(error)}`, ); } }
private sortCollections( collections: Collection[], sortBy: CollectionSortField, sortOrder: SortOrder, ): Collection[] { const sorted = [...collections].sort((a, b) => { let comparison = 0;
switch (sortBy) { case CollectionSortField.NAME: comparison = a.name.value.localeCompare(b.name.value); break; case CollectionSortField.CREATED_AT: comparison = a.createdAt.getTime() - b.createdAt.getTime(); break; case CollectionSortField.UPDATED_AT: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; case CollectionSortField.CARD_COUNT: comparison = a.cardCount - b.cardCount; break; default: comparison = 0; }
return sortOrder === SortOrder.DESC ? -comparison : comparison; });
return sorted; }
async getCollectionsContainingCardForUser( cardId: string, curatorId: string, ): Promise<CollectionContainingCardDTO[]> { try { const allCollections = this.collectionRepository.getAllCollections(); const creatorCollections = allCollections.filter( (collection) => collection.authorId.value === curatorId, );
const collectionsWithCard = creatorCollections.filter((collection) => collection.cardLinks.some( (link) => link.cardId.getStringValue() === cardId, ), );
const result: CollectionContainingCardDTO[] = collectionsWithCard.map( (collection) => { const collectionPublishedRecordId = collection.publishedRecordId; return { id: collection.collectionId.getStringValue(), uri: collectionPublishedRecordId?.uri, name: collection.name.value, description: collection.description?.value, authorId: collection.authorId.value, accessType: collection.accessType, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, }; }, );
return result; } catch (error) { throw new Error( `Failed to get collections containing card: ${error instanceof Error ? error.message : String(error)}`, ); } }
async getCollectionsWithUrl( url: string, options: CollectionForUrlQueryOptions, ): Promise<PaginatedQueryResult<CollectionForUrlRawDTO>> { try { if (!this.cardRepository) { throw new Error( 'Card repository is required for getCollectionsWithUrl', ); }
const allCards = this.cardRepository.getAllCards(); const cardsWithUrl = allCards.filter( (card) => card.isUrlCard && card.url?.value === url, );
const cardIds = new Set( cardsWithUrl.map((card) => card.cardId.getStringValue()), );
const allCollections = this.collectionRepository.getAllCollections(); const collectionsWithUrl = allCollections.filter((collection) => collection.cardLinks.some((link) => cardIds.has(link.cardId.getStringValue()), ), );
// For ADDED_AT sorting, we need to track the max addedAt for each collection let sortedCollections: Collection[]; if (options.sortBy === CollectionSortField.ADDED_AT) { // Create a map of collection -> max addedAt from the matching cards const collectionAddedAtMap = new Map<string, Date>();
for (const collection of collectionsWithUrl) { const matchingCardLinks = collection.cardLinks.filter((link) => cardIds.has(link.cardId.getStringValue()), );
if (matchingCardLinks.length > 0) { const maxAddedAt = matchingCardLinks.reduce((max, link) => { return link.addedAt > max ? link.addedAt : max; }, matchingCardLinks[0]!.addedAt);
collectionAddedAtMap.set( collection.collectionId.getStringValue(), maxAddedAt, ); } }
// Sort by the max addedAt sortedCollections = [...collectionsWithUrl].sort((a, b) => { const aAddedAt = collectionAddedAtMap.get( a.collectionId.getStringValue(), )!; const bAddedAt = collectionAddedAtMap.get( b.collectionId.getStringValue(), )!;
const comparison = aAddedAt.getTime() - bAddedAt.getTime(); return options.sortOrder === SortOrder.DESC ? -comparison : comparison; }); } else { // Use the standard sorting method for other fields sortedCollections = this.sortCollections( collectionsWithUrl, options.sortBy, options.sortOrder, ); }
// Apply pagination const { page, limit } = options; const startIndex = (page - 1) * limit; const endIndex = startIndex + limit; const paginatedCollections = sortedCollections.slice( startIndex, endIndex, );
const items: CollectionForUrlRawDTO[] = paginatedCollections.map( (collection) => { const collectionPublishedRecordId = collection.publishedRecordId; return { id: collection.collectionId.getStringValue(), uri: collectionPublishedRecordId?.uri, name: collection.name.value, description: collection.description?.value, accessType: collection.accessType, authorId: collection.authorId.value, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, }; }, );
return { items, totalCount: sortedCollections.length, hasMore: endIndex < sortedCollections.length, }; } catch (error) { throw new Error( `Failed to get collections with URL: ${error instanceof Error ? error.message : String(error)}`, ); } }
async searchCollections( options: SearchCollectionsOptions, ): Promise<PaginatedQueryResult<CollectionQueryResultDTO>> { try { let allCollections = this.collectionRepository.getAllCollections();
// Apply author filter if provided if (options.authorId) { allCollections = allCollections.filter( (collection) => collection.authorId.value === options.authorId, ); }
// Apply access type filter if provided if (options.accessType) { allCollections = allCollections.filter( (collection) => collection.accessType === options.accessType, ); }
// Apply tokenized search if searchText is provided if (options.searchText && options.searchText.trim()) { const searchWords = options.searchText .trim() .toLowerCase() .split(/\s+/);
allCollections = allCollections.filter((collection) => { const nameText = collection.name.value.toLowerCase(); const descriptionText = collection.description?.value.toLowerCase() || ''; const combinedText = `${nameText} ${descriptionText}`;
// All search words must be found (AND logic) return searchWords.every((word) => combinedText.includes(word)); }); }
const sortedCollections = this.sortCollections( allCollections, options.sortBy, options.sortOrder, );
const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedCollections = sortedCollections.slice( startIndex, endIndex, );
const items: CollectionQueryResultDTO[] = paginatedCollections.map( (collection) => { const collectionPublishedRecordId = collection.publishedRecordId; return { id: collection.collectionId.getStringValue(), uri: collectionPublishedRecordId?.uri, authorId: collection.authorId.value, name: collection.name.value, description: collection.description?.value, accessType: collection.accessType, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, }; }, );
return { items, totalCount: allCollections.length, hasMore: endIndex < allCollections.length, }; } catch (error) { throw new Error( `Failed to search collections: ${error instanceof Error ? error.message : String(error)}`, ); } }
async getOpenCollectionsWithContributor( options: GetOpenCollectionsWithContributorOptions, ): Promise<PaginatedQueryResult<CollectionQueryResultDTO>> { try { const allCollections = this.collectionRepository.getAllCollections();
// Filter for collections where: // 1. User has added cards (via cardLinks.addedBy) // 2. User is NOT the author // 3. Collection is OPEN let contributedCollections = allCollections.filter((collection) => { const hasContributed = collection.cardLinks.some( (link) => link.addedBy.value === options.contributorId, ); const isNotAuthor = collection.authorId.value !== options.contributorId; const isOpen = collection.accessType === 'OPEN';
return hasContributed && isNotAuthor && isOpen; });
// Sort by most recent contribution first, then by the specified field const sortedCollections = [...contributedCollections].sort((a, b) => { // Get most recent contribution date for each collection const aLastContribution = Math.max( ...a.cardLinks .filter((link) => link.addedBy.value === options.contributorId) .map((link) => link.addedAt.getTime()), ); const bLastContribution = Math.max( ...b.cardLinks .filter((link) => link.addedBy.value === options.contributorId) .map((link) => link.addedAt.getTime()), );
// Primary sort: by most recent contribution (DESC) const contributionComparison = bLastContribution - aLastContribution; if (contributionComparison !== 0) return contributionComparison;
// Secondary sort: by the specified field let comparison = 0; switch (options.sortBy) { case CollectionSortField.NAME: comparison = a.name.value.localeCompare(b.name.value); break; case CollectionSortField.CREATED_AT: comparison = a.createdAt.getTime() - b.createdAt.getTime(); break; case CollectionSortField.UPDATED_AT: comparison = a.updatedAt.getTime() - b.updatedAt.getTime(); break; case CollectionSortField.CARD_COUNT: comparison = a.cardCount - b.cardCount; break; } return options.sortOrder === SortOrder.DESC ? -comparison : comparison; });
const startIndex = (options.page - 1) * options.limit; const endIndex = startIndex + options.limit; const paginatedCollections = sortedCollections.slice( startIndex, endIndex, );
const items: CollectionQueryResultDTO[] = paginatedCollections.map( (collection) => { const collectionPublishedRecordId = collection.publishedRecordId; return { id: collection.collectionId.getStringValue(), uri: collectionPublishedRecordId?.uri, authorId: collection.authorId.value, name: collection.name.value, description: collection.description?.value, accessType: collection.accessType, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, }; }, );
return { items, totalCount: sortedCollections.length, hasMore: endIndex < sortedCollections.length, }; } catch (error) { throw new Error( `Failed to get open collections with contributor: ${error instanceof Error ? error.message : String(error)}`, ); } }
async getCollectionContributors( collectionId: string, authorId: string, options: { page: number; limit: number }, ): Promise<PaginatedQueryResult<CollectionContributorDTO>> { try { const allCollections = this.collectionRepository.getAllCollections(); const collection = allCollections.find( (c) => c.collectionId.getStringValue() === collectionId, );
if (!collection) { return { items: [], totalCount: 0, hasMore: false, }; }
// Get unique contributors (excluding author) with their contribution counts const contributorMap = new Map< string, { userId: string; contributionCount: number; lastContributedAt: Date } >();
for (const link of collection.cardLinks) { const contributorId = link.addedBy.value;
// Skip the collection author if (contributorId === authorId) { continue; }
if (contributorMap.has(contributorId)) { const existing = contributorMap.get(contributorId)!; existing.contributionCount++; if (link.addedAt > existing.lastContributedAt) { existing.lastContributedAt = link.addedAt; } } else { contributorMap.set(contributorId, { userId: contributorId, contributionCount: 1, lastContributedAt: link.addedAt, }); } }
// Convert to array and sort by most recent contribution let contributors = Array.from(contributorMap.values()).sort( (a, b) => b.lastContributedAt.getTime() - a.lastContributedAt.getTime(), );
const totalCount = contributors.length;
// Apply pagination const { page, limit } = options; const startIndex = (page - 1) * limit; const endIndex = startIndex + limit; contributors = contributors.slice(startIndex, endIndex);
return { items: contributors, totalCount, hasMore: endIndex < totalCount, }; } catch (error) { throw new Error( `Failed to get collection contributors: ${error instanceof Error ? error.message : String(error)}`, ); } }
async getCollectionsForUrls( urls: string[], ): Promise<CollectionWithMatchedUrlsDTO[]> { return this.queryCollectionsWithMatchedUrls(urls, () => true); }
async getCollectionsForUrlsByAuthor( urls: string[], authorId: string, excludeUrl?: string, ): Promise<CollectionWithMatchedUrlsDTO[]> { return this.queryCollectionsWithMatchedUrls( urls, (collection) => collection.authorId.value === authorId, excludeUrl, ); }
async getOpenCollectionsForUrls( urls: string[], excludeAuthorId?: string, excludeUrl?: string, ): Promise<CollectionWithMatchedUrlsDTO[]> { return this.queryCollectionsWithMatchedUrls( urls, (collection) => collection.accessType === 'OPEN' && (!excludeAuthorId || collection.authorId.value !== excludeAuthorId), excludeUrl, ); }
private queryCollectionsWithMatchedUrls( urls: string[], matchesCollection: (collection: Collection) => boolean, excludeUrl?: string, ): CollectionWithMatchedUrlsDTO[] { const allCards = this.cardRepository?.getAllCards() || []; const allCollections = this.collectionRepository?.getAllCollections() || []; const urlSet = new Set(urls);
// Card ids of URL cards holding the URL being recommended for, so // collections that already contain it can be filtered out const excludedCardIds = excludeUrl ? new Set( allCards .filter( (c) => c.type.value === 'URL' && c.url && c.url.value === excludeUrl, ) .map((c) => c.cardId.getStringValue()), ) : null;
// Map URL card id -> url for cards matching the queried URLs const urlByCardId = new Map<string, string>(); allCards .filter((c) => c.type.value === 'URL' && c.url && urlSet.has(c.url.value)) .forEach((c) => urlByCardId.set(c.cardId.getStringValue(), c.url!.value));
return allCollections .filter(matchesCollection) .filter( (collection) => !excludedCardIds || !collection.cardLinks.some((link) => excludedCardIds.has(link.cardId.getStringValue()), ), ) .map((collection) => { const matchedUrls = [ ...new Set( collection.cardLinks .map((link) => urlByCardId.get(link.cardId.getStringValue())) .filter((url): url is string => !!url), ), ]; return { collection, matchedUrls }; }) .filter(({ matchedUrls }) => matchedUrls.length > 0) .map(({ collection, matchedUrls }) => ({ id: collection.collectionId.getStringValue(), uri: collection.publishedRecordId?.uri, authorId: collection.authorId.value, name: collection.name.value, description: collection.description?.value, accessType: collection.accessType, cardCount: collection.cardCount, createdAt: collection.createdAt, updatedAt: collection.updatedAt, matchedUrls, })); }
async getProfileCollectionCount(authorId: string): Promise<number> { const allCollections = this.collectionRepository?.getAllCollections() || [];
// Count collections created by this user const collectionCount = allCollections.filter( (c) => c.authorId.value === authorId, ).length;
return collectionCount; }
clear(): void { // No separate state to clear }}