-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Provide an helper composable to count elements in a collection #…
- Loading branch information
Showing
3 changed files
with
53 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters