refactor: front end code to unified design
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
+193
-212
@@ -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,
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user