Usage
Advanced Usage
Learn how to build a wrapper around the JS Craft CMS API package.
Custom Wrapper Example
The following example demonstrates how to build a custom wrapper for buildCraftQueryUrl()
in Vue.
This wrapper, useCraftUrlBuilder
, adds custom methods and handles URLs more flexibly.
useCraftUrlBuilder.ts
import { buildCraftQueryUrl } from 'js-craftcms-api';
import { useCraft } from './useApi';
import type { ElementType, ExecutionMethods } from 'js-craftcms-api';
export function useCraftUrlBuilder<T extends ElementType>(elementType: T) {
const queryBuilder = buildCraftQueryUrl(elementType); // Initialize the core builder
const { baseUrl, debug } = useCraft();
return {
...queryBuilder,
// Custom method to build the full URL
buildUrl(execOpt: ExecutionMethods) {
const queryUrl = queryBuilder.buildBaseUrl(execOpt);
const url = `${baseUrl}${queryUrl}`;
if (debug) {
console.log('The built URL is: ' + url);
}
return url;
},
};
}
Explanation
queryBuilder
: UsesbuildCraftQueryUrl()
to initialize the core query builder.baseUrl
anddebug
: These values are retrieved from a customuseCraft()
composable, providing additional configuration in Vue.buildUrl(execOpt: ExecutionMethods)
: Extends the base query builder with abuildUrl
method, which generates the full URL by appendingbaseUrl
and, ifdebug
is enabled, logs the URL to the console.
Make It Your Own
Feel free to build your own. If you create your own wrapper and decide to publish it as an npm package, reach out! I’d love to mention your work. :)