Skip to content

Commit

Permalink
feat: Provide an helper composable to count elements in a collection #…
Browse files Browse the repository at this point in the history
  • Loading branch information
cnouguier authored and claustres committed Sep 20, 2024
1 parent 7973684 commit 6b0e17e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
51 changes: 51 additions & 0 deletions core/client/composables/counter.js
Original file line number Diff line number Diff line change
@@ -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
}
}
1 change: 1 addition & 0 deletions core/client/composables/index.js
Original file line number Diff line number Diff line change
@@ -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'
Expand Down
2 changes: 1 addition & 1 deletion core/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6b0e17e

Please sign in to comment.