Refactored CMS packages to remove a circular dependency (#62)

This commit is contained in:
Giancarlo Buomprisco
2024-09-04 03:10:50 +08:00
committed by GitHub
parent 51a40b6d40
commit d18f810c6e
23 changed files with 193 additions and 83 deletions

View File

@@ -1,5 +1,9 @@
import { CmsClient } from './cms-client';
import { CmsType } from './cms.type';
import { CmsClient, CmsType } from '@kit/cms-types';
/**
* The type of CMS client to use.
*/
const CMS_CLIENT = process.env.CMS_CLIENT as CmsType;
/**
* Creates a CMS client based on the specified type.
@@ -9,61 +13,32 @@ import { CmsType } from './cms.type';
* @throws {Error} If the specified CMS type is unknown.
*/
export async function createCmsClient(
type: CmsType = process.env.CMS_CLIENT as CmsType,
type: CmsType = CMS_CLIENT,
): Promise<CmsClient> {
return cmsClientFactory(type);
}
async function cmsClientFactory(type: CmsType) {
/**
* Creates a CMS client based on the specified type.
*
* @param {CmsType} type - The type of CMS client to create.
* @returns {Promise<CmsClient>} A Promise that resolves to the created CMS client.
*/
async function cmsClientFactory(type: CmsType): Promise<CmsClient> {
switch (type) {
case 'wordpress':
return getWordpressClient();
case 'wordpress': {
const { createWordpressClient } = await import('@kit/wordpress');
case 'keystatic':
return getKeystaticClient();
return createWordpressClient();
}
case 'keystatic': {
const { createKeystaticClient } = await import('@kit/keystatic');
return createKeystaticClient();
}
default:
throw new Error(`Unknown CMS type`);
}
}
async function getWordpressClient() {
const { createWordpressClient } = await import(
'../../wordpress/src/wp-client'
);
return createWordpressClient();
}
async function getKeystaticClient() {
if (
process.env.NEXT_RUNTIME === 'nodejs' ||
process.env.KEYSTATIC_STORAGE_KIND !== 'local'
) {
const { createKeystaticClient } = await import(
'../../keystatic/src/keystatic-client'
);
return createKeystaticClient();
}
console.error(
`[CMS] Keystatic client using "Local" mode is only available in Node.js runtime. Please choose a different CMS client. Returning a mock client instead of throwing an error.`,
);
return mockCMSClient() as unknown as CmsClient;
}
function mockCMSClient() {
return {
getContentItems() {
return Promise.resolve({
items: [],
total: 0,
});
},
getContentItemBySlug() {
return Promise.resolve(undefined);
},
};
}