diff --git a/core/client/composables/counter.js b/core/client/composables/counter.js new file mode 100644 index 000000000..2e9c62dd0 --- /dev/null +++ b/core/client/composables/counter.js @@ -0,0 +1,51 @@ +import _ from 'lodash' +import logger from 'loglevel' +import { ref, watchEffect, onBeforeMount, onBeforeUnmount } from 'vue' +import { api } from '../api.js' + +export function useCounter (options) { + logger.trace(`[KDK] Counter created with options ${options}`) + + // Data + const counter = ref(0) + + // Watch + watchEffect(() => refresh()) + + // Functions + function getService () { + const service = api.getService(options.service.value, options.contextId ? options.contextId.value : null) + if (!service) { + throw new Error('[KDK] Cannot retrieve target service ' + options.service.value) + } + return service + } + function getBaseQuery () { + return options.baseQuery ? options.baseQuery.value : {} + } + function getFilterQuery () { + return options.filterQuery ? options.filterQuery.value : {} + } + async function refresh () { + const query = _.merge(getBaseQuery(), getFilterQuery(), { $limit: 0 }) + logger.trace(`[KDK] Count service ${options.service.value} with query ${query}`) + const response = await getService().find({ query }) + counter.value = response.total + } + + // Hooks + onBeforeMount(async () => { + const service = getService() + service.on('created', refresh) + service.on('removed', refresh) + }) + onBeforeUnmount(() => { + const service = getService() + service.off('created', refresh) + service.off('removed', refresh) + }) + + return { + counter + } +} diff --git a/core/client/composables/index.js b/core/client/composables/index.js index cc070269e..b37323358 100644 --- a/core/client/composables/index.js +++ b/core/client/composables/index.js @@ -1,5 +1,6 @@ export * from './activity.js' export * from './collection.js' +export * from './counter.js' export * from './layout.js' export * from './messages.js' export * from './pwa.js' diff --git a/core/client/index.js b/core/client/index.js index 0e10fb83e..9dd353f17 100644 --- a/core/client/index.js +++ b/core/client/index.js @@ -57,7 +57,7 @@ export default async function initialize () { logger.debug('[KDK] initializing core module') - // Declare the module intiaization states + // Declare the module initialization states Store.set('kdk', { core: { initialized: false }, map: { initialized: false } }) // Initialize singletons that might be used globally first