File size: 3,248 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
import PostType from "../interfaces/post";
export async function executeGraphQLForBlogPosts(
query: string,
): Promise<CmsPost[]> {
const graphQLEndpoint = `${process.env.SF_API_URL}graphql`;
const response = await fetch(graphQLEndpoint, {
method: "POST",
body: JSON.stringify({ query }),
headers: { "Content-Type": "application/json" },
}).then((x) => x.json());
return response["data"]["posts"];
}
export async function getAllPostSlugsFromCms(): Promise<string[]> {
var query = `
query {
posts {
itemDefaultUrl
}
}
`;
const blogPosts = await executeGraphQLForBlogPosts(query);
const slugs = blogPosts.map((x) => x.itemDefaultUrl);
return slugs;
}
function transformImageUrl(url: string) {
if (!url.startsWith("http")) {
url = process.env.SF_URL + url.substring(1);
}
return url;
}
function mapCmsBlog(source: CmsPost): PostType {
return {
content: source.content,
excerpt: source.excerpt,
date: source.dateCreated,
slug: source.itemDefaultUrl,
title: source.title,
author: {
name: source.authorOfPost[0].title,
picture: transformImageUrl(source.authorOfPost[0].picture[0].url),
},
coverImage: transformImageUrl(source.coverImage[0].url),
ogImage: {
url: transformImageUrl(source.openGraphImage[0].url),
},
};
}
export async function getPostBySlugFromCms(slug: string): Promise<PostType> {
const modifiedSlug = slug;
var query = `
query {
posts(_filter: {itemDefaultUrl: {_eq: "${modifiedSlug}"}}) {
id
title
excerpt
content
dateCreated
itemDefaultUrl
openGraphImage {
url
}
coverImage {
url
}
authorOfPost {
title
picture {
url
}
}
}
}
`;
const blogPosts = (await executeGraphQLForBlogPosts(query)).map((x) =>
mapCmsBlog(x),
);
if (blogPosts.length > 0) return blogPosts[0];
return null;
}
export async function getAllPostsFromCms(): Promise<PostType[]> {
var query = `
query {
posts {
id
title
excerpt
content
dateCreated
itemDefaultUrl
openGraphImage {
url
}
coverImage {
url
}
authorOfPost {
title
picture {
url
}
}
}
}
`;
const blogPosts = (await executeGraphQLForBlogPosts(query)).map((x) =>
mapCmsBlog(x),
);
return blogPosts;
}
interface CmsPost {
title: string;
excerpt: string;
dateCreated: string;
content: string;
itemDefaultUrl: string;
openGraphImage: {
url: string;
};
coverImage: {
url: string;
};
authorOfPost: {
title: string;
picture: {
url: string;
};
};
}
|