ghost/ts/classes.ghost.ts

69 lines
2.0 KiB
TypeScript

import * as plugins from './ghost.plugins.js';
import { Post, type IPostOptions } from './classes.post.js';
export interface IGhostConstructorOptions {
baseUrl: string;
contentApiKey: string;
adminApiKey: string;
}
export class Ghost {
public options: IGhostConstructorOptions;
public adminApi: any;
public contentApi: any;
constructor(optionsArg: IGhostConstructorOptions) {
this.options = optionsArg;
this.adminApi = new plugins.GhostAdminAPI({
url: this.options.baseUrl,
key: this.options.adminApiKey,
version: 'v3',
});
this.contentApi = new plugins.GhostContentAPI({
url: this.options.baseUrl,
key: this.options.contentApiKey,
version: 'v3',
});
}
public async getPosts(limit: number = 1000): Promise<Post[]> {
try {
const postsData = await this.contentApi.posts.browse({ limit, include: 'tags,authors' });
return postsData.map((postData: IPostOptions) => new Post(this, postData));
} catch (error) {
console.error('Error fetching posts:', error);
throw error;
}
}
public async getPostById(id: string): Promise<Post> {
try {
const postData = await this.contentApi.posts.read({ id });
return new Post(postData, this.adminApi);
} catch (error) {
console.error(`Error fetching post with id ${id}:`, error);
throw error;
}
}
public async createPost(postData: IPostOptions): Promise<Post> {
try {
const createdPostData = await this.adminApi.posts.add(postData);
return new Post(createdPostData, this.adminApi);
} catch (error) {
console.error('Error creating post:', error);
throw error;
}
}
public async createPostFromHtml(optionsArg: { title: string; html: string }) {
const postData = await this.adminApi.posts.add(
{ title: optionsArg.title, html: optionsArg.html },
{ source: 'html' } // Tell the API to use HTML as the content source, instead of Lexical
);
return new Post(this, postData);
}
}