oxen-website/services/blog.ts

82 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-01-29 03:50:49 +01:00
import { ContentfulClientApi, createClient } from 'contentful';
import moment from 'moment';
import { IAuthor, IFigureImage, IPost } from '../types/blog';
export class BlogApi {
client: ContentfulClientApi;
constructor() {
this.client = createClient({
space: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
});
}
2021-01-31 11:02:19 +01:00
public async fetchBlogEntries(): Promise<Array<IPost>> {
2021-01-29 03:50:49 +01:00
return this.client
.getEntries({
// content_type: 'blogPost', // only fetch blog post entry
})
.then(entries => {
console.log('blog ➡️ entries:', entries);
if (entries && entries.items && entries.items.length > 0) {
const blogPosts = entries.items.map(entry => this.convertPost(entry));
return blogPosts;
}
return [];
});
}
2021-01-31 11:02:19 +01:00
public async fetchBlogById(id): Promise<IPost> {
2021-01-29 03:50:49 +01:00
return this.client.getEntry(id).then(entry => {
if (entry) {
const post = this.convertPost(entry);
return post;
}
return null;
});
}
2021-01-31 11:02:19 +01:00
public convertImage = (rawImage): IFigureImage =>
rawImage
? {
imageUrl: rawImage.file.url.replace('//', 'http://'), // may need to put null check as well here
description: rawImage.description,
title: rawImage.title,
}
: null;
2021-01-29 03:50:49 +01:00
2021-01-31 11:02:19 +01:00
public convertAuthor = (rawAuthor): IAuthor =>
rawAuthor
? {
name: rawAuthor.name,
shortBio: rawAuthor.shortBio,
position: rawAuthor.position,
email: rawAuthor.email,
twitter: rawAuthor?.twitter ?? null,
facebook: rawAuthor.facebook,
github: rawAuthor.github,
}
: null;
2021-01-29 03:50:49 +01:00
2021-01-31 11:02:19 +01:00
public convertPost = (rawData): IPost => {
2021-01-29 03:50:49 +01:00
const rawPost = rawData.fields;
const rawFeatureImage = rawPost.featureImage
? rawPost.featureImage.fields
: null;
const rawAuthor = rawPost.author ? rawPost.author.fields : null;
2021-01-31 11:02:19 +01:00
2021-01-29 03:50:49 +01:00
return {
id: rawData.sys.id,
body: rawPost.body,
2021-01-31 11:02:19 +01:00
subtitle: rawPost.subtitle,
2021-01-29 03:50:49 +01:00
publishedDate: moment(rawPost.publishedDate).format('DD MMM YYYY'),
slug: rawPost.slug,
2021-01-31 11:02:19 +01:00
tags: rawPost?.tags ?? [],
2021-01-29 03:50:49 +01:00
title: rawPost.title,
featureImage: this.convertImage(rawFeatureImage),
author: this.convertAuthor(rawAuthor),
};
};
}