@vtex/client-cms
Version:
A client to fetch data from VTEX CMS.
88 lines (66 loc) • 2.05 kB
text/typescript
import type {
Options,
ContentTypes,
ContentPage,
ContentData,
Locator,
ContentTypeOptions,
} from '../utils/types'
import { fetchAPI } from '../utils/fetch'
class ClientCMS {
private options: Options
private url: string
constructor({
tenant,
builder = 'faststore',
workspace = 'master',
host = '',
}: Options) {
this.options = { tenant, builder, workspace, host }
this.url = this.getApiUrl()
}
public getOptions() {
return this.options
}
public getApiUrl = () => {
const { tenant, workspace } = this.options
return `https://${workspace}--${tenant}.myvtex.com`
}
public fetch<T>(path = '', params?: URLSearchParams) {
const { builder, host } = this.options
const pathParams = params ? `?${params.toString()}` : ''
const requestInit = host ? { headers: { Host: host } } : undefined
return fetchAPI<T>(
`${this.url}/_v/cms/api/${builder}/${path}${pathParams}`,
requestInit
)
}
public getAllContentTypeIds = async (): Promise<string[]> => {
const { contentTypes } = await this.fetch<ContentTypes>()
return contentTypes.map((contentType) => contentType.id)
}
public getCMSPagesByContentType = (
contentType: string,
{ page = 1, perPage = 10, filters = {} }: Partial<ContentTypeOptions> = {}
) => {
const params = new URLSearchParams()
params.set('page', page.toString())
params.set('per_page', perPage.toString())
for (const [key, value] of Object.entries(filters)) {
params.set(`filters[${key}]`, value)
}
return this.fetch<ContentPage>(contentType, params)
}
public getCMSPage = async (locator: Locator) => {
const { documentId, contentType } = locator
const params = new URLSearchParams()
if (locator.releaseId) {
params.set('releaseId', locator.releaseId)
}
if (locator.versionId) {
params.set('versionId', locator.versionId)
}
return this.fetch<ContentData>(`${contentType}/${documentId}`, params)
}
}
export default ClientCMS