Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created July 11, 2020 17:20
Show Gist options
  • Save mattmccray/9f0fdadd99d42d367d5eae7cca7a22aa to your computer and use it in GitHub Desktop.
Save mattmccray/9f0fdadd99d42d367d5eae7cca7a22aa to your computer and use it in GitHub Desktop.
TypeScript class for using the CockpitCMS API
const _tokenCache = new WeakMap<CockpitAPI, string>()
export class CockpitAPI {
constructor(public readonly baseUrl: string, token: string) {
_tokenCache.set(this, token)
}
setToken(token: string) {
_tokenCache.set(this, token)
}
getCollection<T>(name: string, options?: ICollectionRequestOptions) {
const info = !!options
? { body: JSON.stringify(options) }
: void 0
return this.fetch<ICollectionResponse<T>>(`collections/get/${name}`, info)
}
getCollectionItem(name: string, _id: string) {
return this.getCollection(name, {
filter: { _id },
limit: 1
})
}
saveCollectionItem<T>(name: string, data: any) {
return this.fetch<ICollectionItem<T>>(`collections/save/${name}`, {
body: JSON.stringify({ data })
})
}
removeCollectionItem(name: string, _id: string) {
return this.fetch<ICollectionResponse>(`collections/remove/${name}`, {
body: JSON.stringify({
filter: { _id }
})
})
}
submitForm(formName: string, form: any) {
return this.fetch(`forms/submit/${formName}`, {
body: JSON.stringify({ form })
})
}
async fetch<T = any>(path: string, info: RequestInit = {}): Promise<T> {
const token = _tokenCache.get(this)
if (!token || token === "") throw new Error("Access Token required.")
const headers = { 'Content-Type': 'application/json', 'Cockpit-Token': token }
if ('headers' in info) {
info.headers = Object.assign(info.headers, headers)
}
else {
info = Object.assign(info, { headers })
}
if ('body' in info) {
info.method = "post"
}
return await (await fetch(`${this.baseUrl}/api/${path}`, info)).json()
}
}
export default CockpitAPI
type ICollectionItem<T> = T & {
_id: string
_by?: string
_created?: number
_mby?: string
_modified?: number
}
interface ICollectionResponse<T = {}> {
entries: ICollectionItem<T>[]
fields: {
[name: string]: {
localize: boolean
name: string
options: any
type: TFieldType
}
},
total: number
}
interface ICollectionRequestOptions {
filter?: any //{published:true},
fields?: any //{fieldA: 1, fieldB: 1},
limit?: number
skip?: number
sort?: any //{_created:-1},
populate?: number // resolve linked collection items
lang?: string // return normalized language fields (fieldA_de => fieldA)
}
type TFieldType
= "access-list"
| "account-link"
| "asset"
| "boolean"
| "code"
| "collection-link"
| "color"
| "colortag"
| "date"
| "file"
| "gallery"
| "html"
| "image"
| "layout"
| "layout-grid"
| "location"
| "markdown"
| "multipleselect"
| "object"
| "password"
| "rating"
| "repeater"
| "select"
| "set"
| "tags"
| "text"
| "textarea"
| "time"
| "wysiwyg"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment