refactor: front end code to unified design

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-06-28 12:21:09 -04:00
parent 08c1de9723
commit 80a8dac2fd
21 changed files with 1087 additions and 1151 deletions
+78 -144
View File
@@ -4,9 +4,14 @@
import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import {
type ServiceIdentifier,
type CollectionIdentifier,
type ListFilter,
type ListSort,
} from '../types'
import { collectionService } from '../services'
import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
import type { SourceSelector, ListFilter, ListSort } from '../types'
export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
// State
@@ -33,101 +38,61 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
*/
const collectionsByService = computed(() => {
const groups: Record<string, CollectionObject[]> = {}
Object.values(_collections.value).forEach((collection) => {
const serviceKey = `${collection.provider}:${collection.service}`
if (!groups[serviceKey]) {
groups[serviceKey] = []
}
groups[serviceKey].push(collection)
const serviceCollections = (groups[serviceKey] ??= [])
serviceCollections.push(collection)
})
return groups
})
/**
* Get a specific collection from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Collection object or null
*/
function collection(provider: string, service: string | number, identifier: string | number, retrieve: boolean = false): CollectionObject | null {
const key = identifierKey(provider, service, identifier)
if (retrieve === true && !_collections.value[key]) {
console.debug(`[Chrono Manager][Store] - Force fetching collection "${key}"`)
fetch(provider, service, identifier)
function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null {
if (retrieve === true && !_collections.value[target]) {
console.debug(`[Chrono Manager][Store] - Force fetching collection "${target}"`)
fetch([target])
}
return _collections.value[key] || null
return _collections.value[target] || null
}
/**
* Get all collections for a specific service
*
* @param provider - provider identifier
* @param service - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of collection objects
*/
function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] {
const serviceKeyPrefix = `${provider}:${service}:`
const serviceCollections = Object.entries(_collections.value)
.filter(([key]) => key.startsWith(serviceKeyPrefix))
.map(([_, collection]) => collection)
const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier
const serviceCollections = Object.values(_collections.value)
.filter(collection => `${collection.provider}:${collection.service}` === serviceIdentifier)
if (retrieve === true && serviceCollections.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${provider}:${service}"`)
const sources: SourceSelector = {
[provider]: {
[String(service)]: true
}
}
list(sources)
console.debug(`[Chrono Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`)
list([serviceIdentifier])
}
return serviceCollections
}
/**
* Create unique key for a collection
* Retrieve all or specific collections, optionally filtered by service/collection identifiers
*/
function identifierKey(provider: string, service: string | number | null, identifier: string | number | null): string {
return `${provider}:${service ?? ''}:${identifier ?? ''}`
}
// Actions
/**
* Retrieve all or specific collections, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
*
* @returns Promise with collection object list keyed by provider, service, and collection identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
transceiving.value = true
try {
const response = await collectionService.list({ sources, filter, sort })
// Flatten nested structure: provider:service:collection -> "provider:service:collection": object
const collections: Record<string, CollectionObject> = {}
Object.entries(response).forEach(([_providerId, providerServices]) => {
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
const key = identifierKey(collectionObj.provider, collectionObj.service, collectionObj.identifier)
collections[key] = collectionObj
collections[collectionObj.identifier] = collectionObj
})
})
})
// Merge retrieved collections into state
_collections.value = { ..._collections.value, ...collections }
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections')
@@ -139,29 +104,23 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
transceiving.value = false
}
}
/**
* Retrieve a specific collection by provider, service, and identifier
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
*
* @returns Promise with collection object
* Retrieve specific collections by their identifiers
*/
async function fetch(provider: string, service: string | number, identifier: string | number): Promise<CollectionObject> {
async function fetch(targets: CollectionIdentifier[]): Promise<Record<string, CollectionObject>> {
transceiving.value = true
try {
const response = await collectionService.fetch({ provider, service, collection: identifier })
// Merge fetched collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
const response = await collectionService.fetch({ targets })
console.debug('[Chrono Manager][Store] - Successfully fetched collection:', key)
Object.values(response).forEach(collectionObj => {
_collections.value[collectionObj.identifier] = collectionObj
})
console.debug('[Chrono Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', '))
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to fetch collection:', error)
console.error('[Chrono Manager][Store] - Failed to fetch collections:', error)
throw error
} finally {
transceiving.value = false
@@ -169,18 +128,14 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
}
/**
* Retrieve collection availability status for a given source selector
*
* @param sources - source selector to check availability for
*
* @returns Promise with collection availability status
* Retrieve collection availability status for the given collection identifiers
*/
async function extant(sources: SourceSelector) {
async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> {
transceiving.value = true
try {
const response = await collectionService.extant({ sources })
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'collections')
const response = await collectionService.extant({ targets })
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'collections')
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check collections:', error)
@@ -191,30 +146,20 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
}
/**
* Create a new collection with given provider, service, and data
*
* @param provider - provider identifier for the new collection
* @param service - service identifier for the new collection
* @param collection - optional parent collection identifier
* @param data - collection properties for creation
*
* @returns Promise with created collection object
* Create a new collection with given provider, service, and properties
*/
async function create(provider: string, service: string | number, collection: string | number | null, data: CollectionPropertiesObject): Promise<CollectionObject> {
async function create(provider: string, service: string | number, properties: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true
try {
const response = await collectionService.create({
provider,
service,
collection,
properties: data
const response = await collectionService.create({
provider,
service,
properties: properties.toJson(),
})
// Merge created collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully created collection:', key)
_collections.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully created collection:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create collection:', error)
@@ -225,30 +170,19 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
}
/**
* Update an existing collection with given provider, service, identifier, and data
*
* @param provider - provider identifier for the collection to update
* @param service - service identifier for the collection to update
* @param identifier - collection identifier for the collection to update
* @param data - collection properties for update
*
* @returns Promise with updated collection object
* Update an existing collection with given target and properties
*/
async function update(provider: string, service: string | number, identifier: string | number, data: CollectionPropertiesObject): Promise<CollectionObject> {
async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true
try {
const response = await collectionService.update({
provider,
service,
identifier,
properties: data
const response = await collectionService.update({
target,
properties: properties.toJson(),
})
// Merge updated collection into state
const key = identifierKey(response.provider, response.service, response.identifier)
_collections.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully updated collection:', key)
_collections.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully updated collection:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update collection:', error)
@@ -259,24 +193,28 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
}
/**
* Delete a collection by provider, service, and identifier
*
* @param provider - provider identifier for the collection to delete
* @param service - service identifier for the collection to delete
* @param identifier - collection identifier for the collection to delete
*
* @returns Promise with deletion result
* Delete a collection by identifier.
*/
async function remove(provider: string, service: string | number, identifier: string | number): Promise<any> {
async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> {
transceiving.value = true
try {
await collectionService.delete({ provider, service, identifier })
// Remove deleted collection from state
const key = identifierKey(provider, service, identifier)
delete _collections.value[key]
const response = await collectionService.delete({ target, options: { force } })
console.debug('[Chrono Manager][Store] - Successfully deleted collection:', key)
if (response !== true && !(response instanceof CollectionObject)) {
console.warn('[Chrono Manager][Store] - Delete failed. Received unexpected response from delete operation:', response)
return false
}
delete _collections.value[target]
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully moved collection', target, '->', response.identifier)
return response
}
console.debug('[Chrono Manager][Store] - Successfully deleted collection:', target)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete collection:', error)
throw error
@@ -285,17 +223,13 @@ export const useCollectionsStore = defineStore('chronoCollectionsStore', () => {
}
}
// Return public API
return {
// State (readonly)
transceiving: readonly(transceiving),
// Getters
count,
has,
collections,
collectionsByService,
collectionsForService,
// Actions
collection,
list,
fetch,
+193 -212
View File
@@ -6,7 +6,14 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import { entityService } from '../services'
import { EntityObject } from '../models'
import type { SourceSelector, ListFilter, ListSort, ListRange } from '../types/common'
import type {
CollectionIdentifier,
EntityIdentifier,
ListFilter,
ListRange,
ListSort,
} from '../types/common'
import type { EntityPropertiesInterface } from '@/types/entity'
export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
// State
@@ -30,95 +37,44 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
/**
* Get a specific entity from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifier - entity identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Entity object or null
*/
function entity(provider: string, service: string | number, collection: string | number, identifier: string | number, retrieve: boolean = false): EntityObject | null {
const key = identifierKey(provider, service, collection, identifier)
if (retrieve === true && !_entities.value[key]) {
console.debug(`[Chrono Manager][Store] - Force fetching entity "${key}"`)
fetch(provider, service, collection, [identifier])
function entity(target: EntityIdentifier, retrieve: boolean = false): EntityObject | null {
if (retrieve === true && !_entities.value[target]) {
console.debug(`[Chrono Manager][Store] - Force fetching entity "${target}"`)
fetch([target])
}
return _entities.value[key] || null
return _entities.value[target] || null
}
/**
* Get all entities for a specific collection
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of entity objects
*/
function entitiesForCollection(provider: string, service: string | number, collection: string | number, retrieve: boolean = false): EntityObject[] {
const collectionKeyPrefix = `${provider}:${service}:${collection}:`
function entitiesForCollection(target: CollectionIdentifier, retrieve: boolean = false): EntityObject[] {
const collectionEntities = Object.entries(_entities.value)
.filter(([key]) => key.startsWith(collectionKeyPrefix))
.filter(([key]) => key.startsWith(`${target}:`))
.map(([_, entity]) => entity)
if (retrieve === true && collectionEntities.length === 0) {
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${provider}:${service}:${collection}"`)
const sources: SourceSelector = {
[provider]: {
[String(service)]: {
[String(collection)]: true
}
}
}
list(sources)
console.debug(`[Chrono Manager][Store] - Force fetching entities for collection "${target}"`)
list([target])
}
return collectionEntities
}
/**
* Create unique key for an entity
* Retrieve all or specific entities, optionally filtered by source collection identifiers
*/
function identifierKey(provider: string, service: string | number, collection: string | number, identifier: string | number): string {
return `${provider}:${service}:${collection}:${identifier}`
}
// Actions
/**
* Retrieve all or specific entities, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
* @param range - optional list range
*
* @returns Promise with entity object list keyed by identifier
*/
async function list(sources?: SourceSelector, filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
async function list(sources: CollectionIdentifier[], filter?: ListFilter, sort?: ListSort, range?: ListRange): Promise<Record<string, EntityObject>> {
transceiving.value = true
try {
const response = await entityService.list({ sources, filter, sort, range })
// Flatten nested structure: provider:service:collection:entity -> "provider:service:collection:entity": object
const entities: Record<string, EntityObject> = {}
Object.entries(response).forEach(([providerId, providerServices]) => {
Object.entries(providerServices).forEach(([serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([collectionId, collectionEntities]) => {
Object.entries(collectionEntities).forEach(([entityId, entityData]) => {
const key = identifierKey(providerId, serviceId, collectionId, entityId)
entities[key] = entityData
})
})
})
})
// Merge retrieved entities into state
_entities.value = { ..._entities.value, ...entities }
await entityService.listStream({ sources, filter, sort, range }, (entity: EntityObject) => {
_entities.value[entity.identifier] = entity
entities[entity.identifier] = entity
})
console.debug('[Chrono Manager][Store] - Successfully retrieved', Object.keys(entities).length, 'entities')
return entities
@@ -129,28 +85,19 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
transceiving.value = false
}
}
/**
* Retrieve specific entities by provider, service, collection, and identifiers
*
* @param provider - provider identifier
* @param service - service identifier
* @param collection - collection identifier
* @param identifiers - array of entity identifiers to fetch
*
* @returns Promise with entity objects keyed by identifier
* Retrieve specific entities by their identifiers
*/
async function fetch(provider: string, service: string | number, collection: string | number, identifiers: (string | number)[]): Promise<Record<string, EntityObject>> {
async function fetch(targets: EntityIdentifier[]): Promise<Record<string, EntityObject>> {
transceiving.value = true
try {
const response = await entityService.fetch({ provider, service, collection, identifiers })
// Merge fetched entities into state
const response = await entityService.fetch({ targets })
const entities: Record<string, EntityObject> = {}
Object.entries(response).forEach(([identifier, entityData]) => {
const key = identifierKey(provider, service, collection, identifier)
entities[key] = entityData
_entities.value[key] = entityData
Object.entries(response).forEach(([identifier, entity]) => {
entities[identifier] = entity
_entities.value[identifier] = entity
})
console.debug('[Chrono Manager][Store] - Successfully fetched', Object.keys(entities).length, 'entities')
@@ -164,16 +111,12 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
}
/**
* Retrieve entity availability status for a given source selector
*
* @param sources - source selector to check availability for
*
* @returns Promise with entity availability status
* Retrieve entity availability status for a given set of entity identifiers
*/
async function extant(sources: SourceSelector) {
async function extant(targets: EntityIdentifier[]) {
transceiving.value = true
try {
const response = await entityService.extant({ sources })
const response = await entityService.extant({ targets })
console.debug('[Chrono Manager][Store] - Successfully checked entity availability')
return response
} catch (error: any) {
@@ -184,132 +127,28 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
}
}
/**
* Create a new entity with given provider, service, collection, and data
*
* @param provider - provider identifier for the new entity
* @param service - service identifier for the new entity
* @param collection - collection identifier for the new entity
* @param data - entity properties for creation
*
* @returns Promise with created entity object
*/
async function create(provider: string, service: string | number, collection: string | number, data: any): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.create({ provider, service, collection, properties: data })
// Add created entity to state
const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully created entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Update an existing entity with given provider, service, collection, identifier, and data
*
* @param provider - provider identifier for the entity to update
* @param service - service identifier for the entity to update
* @param collection - collection identifier for the entity to update
* @param identifier - entity identifier for the entity to update
* @param data - entity properties for update
*
* @returns Promise with updated entity object
*/
async function update(provider: string, service: string | number, collection: string | number, identifier: string | number, data: any): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.update({ provider, service, collection, identifier, properties: data })
// Update entity in state
const key = identifierKey(response.provider, response.service, response.collection, response.identifier)
_entities.value[key] = response
console.debug('[Chrono Manager][Store] - Successfully updated entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Delete an entity by provider, service, collection, and identifier
*
* @param provider - provider identifier for the entity to delete
* @param service - service identifier for the entity to delete
* @param collection - collection identifier for the entity to delete
* @param identifier - entity identifier for the entity to delete
*
* @returns Promise with deletion result
*/
async function remove(provider: string, service: string | number, collection: string | number, identifier: string | number): Promise<any> {
transceiving.value = true
try {
const response = await entityService.delete({ provider, service, collection, identifier })
// Remove entity from state
const key = identifierKey(provider, service, collection, identifier)
delete _entities.value[key]
console.debug('[Chrono Manager][Store] - Successfully deleted entity:', key)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Retrieve delta changes for entities
*
* @param sources - source selector for delta check
*
* @returns Promise with delta changes (additions, modifications, deletions)
*
* Note: Delta returns only identifiers, not full entities.
* Caller should fetch full entities for additions/modifications separately.
*/
async function delta(sources: SourceSelector) {
async function delta(targets: (CollectionIdentifier | EntityIdentifier)[]) {
transceiving.value = true
try {
const response = await entityService.delta({ sources })
// Process delta and update store
Object.entries(response).forEach(([provider, providerData]) => {
// Skip if no changes for provider
const response = await entityService.delta({ targets })
Object.entries(response).forEach(([, providerData]) => {
if (providerData === false) return
Object.entries(providerData).forEach(([service, serviceData]) => {
// Skip if no changes for service
Object.entries(providerData).forEach(([, serviceData]) => {
if (serviceData === false) return
Object.entries(serviceData).forEach(([collection, collectionData]) => {
// Skip if no changes for collection
Object.entries(serviceData).forEach(([, collectionData]) => {
if (collectionData === false) return
// Process deletions (remove from store)
if (collectionData.deletions && collectionData.deletions.length > 0) {
collectionData.deletions.forEach((identifier) => {
const key = identifierKey(provider, service, collection, identifier)
delete _entities.value[key]
delete _entities.value[identifier]
})
}
// Note: additions and modifications contain only identifiers
// The caller should fetch full entities using the fetch() method
})
})
})
@@ -324,16 +163,156 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
}
}
// Return public API
/**
* Create a new empty entity object
*/
function fresh(): EntityObject {
return new EntityObject()
}
/**
* Create a new entity with given collection identifier and properties
*/
async function create(target: CollectionIdentifier, properties: EntityPropertiesInterface): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.create({ target, properties })
_entities.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully created entity:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to create entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Update an existing entity with given entity identifier and properties
*/
async function update(target: EntityIdentifier, properties: EntityPropertiesInterface): Promise<EntityObject> {
transceiving.value = true
try {
const response = await entityService.update({ target, properties })
_entities.value[response.identifier] = response
console.debug('[Chrono Manager][Store] - Successfully updated entity:', response.identifier)
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to update entity:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Delete entities by their identifiers.
*/
async function remove(targets: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> {
transceiving.value = true
try {
const response = await entityService.delete({ targets })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = []
Object.entries(response).forEach(([targetIdentifier, result]) => {
const originalIdentifier = targetIdentifier as EntityIdentifier
if (!result.disposition || result.disposition === 'error') {
console.warn(`[Chrono Manager][Store] - Entity delete on "${originalIdentifier}" returned an error: ${result.error})`)
failures.push(originalIdentifier)
return
}
if (result.disposition !== 'moved' && result.disposition !== 'deleted') {
console.warn(`[Chrono Manager][Store] - Entity delete on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`)
failures.push(originalIdentifier)
return
}
const cachedEntity = _entities.value[originalIdentifier]
if (result.disposition === 'moved' && cachedEntity && result.mutation) {
const movedEntity = cachedEntity.clone().fromJson({
...cachedEntity.toJson(),
collection: result.destination,
identifier: result.mutation,
})
_entities.value[result.mutation] = movedEntity
}
delete _entities.value[originalIdentifier]
successes.push(originalIdentifier)
})
console.debug('[Chrono Manager][Store] - Successfully deleted', successes.length, 'entities')
return { successes, failures }
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to delete entities:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Move entities to another collection.
*/
async function move(target: CollectionIdentifier, sources: EntityIdentifier[]): Promise<{ successes: EntityIdentifier[], failures: EntityIdentifier[] }> {
transceiving.value = true
try {
const response = await entityService.move({ target, sources })
const successes: EntityIdentifier[] = []
const failures: EntityIdentifier[] = []
Object.entries(response).forEach(([sourceIdentifier, result]) => {
const originalIdentifier = sourceIdentifier as EntityIdentifier
if (!result.disposition || result.disposition === 'error') {
console.warn(`[Chrono Manager][Store] - Entity move on "${originalIdentifier}" returned an error: ${result.error})`)
failures.push(originalIdentifier)
return
}
if (result.disposition !== 'moved') {
console.warn(`[Chrono Manager][Store] - Entity move on "${originalIdentifier}" returned invalid disposition: ${result.disposition})`)
failures.push(originalIdentifier)
return
}
const cachedEntity = _entities.value[originalIdentifier]
if (cachedEntity && result.mutation) {
const movedEntity = cachedEntity.clone().fromJson({
...cachedEntity.toJson(),
collection: result.destination,
identifier: result.mutation,
})
_entities.value[result.mutation] = movedEntity
delete _entities.value[originalIdentifier]
}
successes.push(originalIdentifier)
})
console.debug('[Chrono Manager][Store] - Successfully moved', successes.length, 'entities')
return { successes, failures }
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to move entities:', error)
throw error
} finally {
transceiving.value = false
}
}
return {
// State (readonly)
transceiving: readonly(transceiving),
// Getters
count,
has,
entities,
entitiesForCollection,
// Actions
entity,
list,
fetch,
@@ -342,5 +321,7 @@ export const useEntitiesStore = defineStore('chronoEntitiesStore', () => {
update,
delete: remove,
delta,
fresh,
move,
}
})
+7 -7
View File
@@ -6,7 +6,7 @@ import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import { providerService } from '../services'
import { ProviderObject } from '../models/provider'
import type { SourceSelector } from '../types'
import type { ProviderIdentifier } from '../types'
export const useProvidersStore = defineStore('chronoProvidersStore', () => {
// State
@@ -54,10 +54,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
*
* @returns Promise with provider object list keyed by provider identifier
*/
async function list(sources?: SourceSelector): Promise<Record<string, ProviderObject>> {
async function list(targets?: ProviderIdentifier[]): Promise<Record<string, ProviderObject>> {
transceiving.value = true
try {
const providers = await providerService.list({ sources })
const providers = await providerService.list({ targets })
// Merge retrieved providers into state
_providers.value = { ..._providers.value, ...providers }
@@ -82,7 +82,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
async function fetch(identifier: string): Promise<ProviderObject> {
transceiving.value = true
try {
const provider = await providerService.fetch({ identifier })
const provider = await providerService.fetch({ target: identifier })
// Merge fetched provider into state
_providers.value[provider.identifier] = provider
@@ -104,10 +104,10 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
*
* @returns Promise with provider availability status
*/
async function extant(sources: SourceSelector) {
async function extant(targets: ProviderIdentifier[]) {
transceiving.value = true
try {
const response = await providerService.extant({ sources })
const response = await providerService.extant({ targets })
Object.entries(response).forEach(([providerId, providerStatus]) => {
if (providerStatus === false) {
@@ -115,7 +115,7 @@ export const useProvidersStore = defineStore('chronoProvidersStore', () => {
}
})
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'providers')
console.debug('[Chrono Manager][Store] - Successfully checked', targets ? targets.length : 0, 'providers')
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check providers:', error)
+32 -16
View File
@@ -7,7 +7,8 @@ import { defineStore } from 'pinia'
import { serviceService } from '../services'
import { ServiceObject } from '../models/service'
import type {
SourceSelector,
CollectionIdentifier,
ServiceIdentifier,
ServiceInterface,
} from '../types'
@@ -55,20 +56,30 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
* @returns Service object or null
*/
function service(provider: string, identifier: string | number, retrieve: boolean = false): ServiceObject | null {
const key = identifierKey(provider, identifier)
if (retrieve === true && !_services.value[key]) {
console.debug(`[Chrono Manager][Store] - Force fetching service "${key}"`)
fetch(provider, identifier)
return serviceByIdentifier(identifierKey(provider, identifier), retrieve)
}
/**
* Get a service from store by its unique identifier, with optional retrieval
*/
function serviceByIdentifier(identifier: ServiceIdentifier, retrieve: boolean = false): ServiceObject | null {
if (retrieve === true && !_services.value[identifier]) {
console.debug(`[Chrono Manager][Store] - Force fetching service "${identifier}"`)
const separatorIndex = identifier.indexOf(':')
const provider = identifier.slice(0, separatorIndex)
const serviceIdentifier = identifier.slice(separatorIndex + 1)
void fetch(provider, serviceIdentifier)
}
return _services.value[key] || null
return _services.value[identifier] ?? null
}
/**
* Unique key for a service
*/
function identifierKey(provider: string, identifier: string | number | null): string {
return `${provider}:${identifier ?? ''}`
function identifierKey(provider: string, identifier: string | number | null): ServiceIdentifier {
return `${provider}:${identifier ?? ''}` as ServiceIdentifier
}
// Actions
@@ -80,10 +91,10 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
*
* @returns Promise with service object list keyed by provider and service identifier
*/
async function list(sources?: SourceSelector): Promise<Record<string, ServiceObject>> {
async function list(targets?: ServiceIdentifier[] | CollectionIdentifier[]): Promise<Record<string, ServiceObject>> {
transceiving.value = true
try {
const response = await serviceService.list({ sources })
const response = await serviceService.list({ targets })
// Flatten nested structure: provider-id: { service-id: object } -> "provider-id:service-id": object
const services: Record<string, ServiceObject> = {}
@@ -141,12 +152,12 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
*
* @returns Promise with service availability status
*/
async function extant(sources: SourceSelector) {
async function extant(targets: ServiceIdentifier[]) {
transceiving.value = true
try {
const response = await serviceService.extant({ sources })
const response = await serviceService.extant({ targets })
console.debug('[Chrono Manager][Store] - Successfully checked', sources ? Object.keys(sources).length : 0, 'services')
console.debug('[Chrono Manager][Store] - Successfully checked', targets?.length ?? 0, 'services')
return response
} catch (error: any) {
console.error('[Chrono Manager][Store] - Failed to check services:', error)
@@ -192,10 +203,14 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
*
* @returns Promise with updated service object
*/
async function update(provider: string, identifier: string | number, data: Partial<ServiceInterface>): Promise<ServiceObject> {
async function update(provider: string, identifier: string | number, delta: boolean, data: ServiceObject | Partial<ServiceInterface>): Promise<ServiceObject> {
transceiving.value = true
try {
const service = await serviceService.update({ provider, identifier, data })
const payload: Partial<ServiceInterface> = data instanceof ServiceObject
? (delta ? data.toJson(true) : data.toJson())
: data
const service = await serviceService.update({ provider, identifier, delta, data: payload })
// Merge updated service into state
const key = identifierKey(service.provider, service.identifier)
@@ -249,6 +264,7 @@ export const useServicesStore = defineStore('chronoServicesStore', () => {
// Actions
service,
serviceByIdentifier,
list,
fetch,
extant,