Skip to content

Instantly share code, notes, and snippets.

@snide
Created May 30, 2023 17:42
Show Gist options
  • Save snide/eedd67ee9ae3a483b292ebef92161f00 to your computer and use it in GitHub Desktop.
Save snide/eedd67ee9ae3a483b292ebef92161f00 to your computer and use it in GitHub Desktop.
import { allBlogs, allDocs } from '~/.contentlayer/generated';
import { DocHeading } from '~/contentlayer.config';
import { Blog as XataBlog, Docs as XataDoc, getXataClient } from '~/utils/xata';
const xata = getXataClient();
export const getGitSha = () =>
process.env.NODE_ENV === 'development' ? 'development' : process.env.VERCEL_GIT_COMMIT_SHA;
export const blogSync = async () => {
const gitSha = process.env.NODE_ENV === 'development' ? 'development' : process.env.VERCEL_GIT_COMMIT_SHA;
const blogsToDelete = await xata.db.blog.filter({ gitSha }).getAll();
for (const blogToDelete of blogsToDelete) {
console.log(`Deleting blog: ${blogToDelete.slug}`);
await xata.db.blog.delete(blogToDelete.id);
}
for (const blog of allBlogs) {
const blogData: Partial<XataBlog> = {
title: blog.title,
description: blog.description,
author: blog.author,
content: blog.body.raw,
date: new Date(blog.date),
image: blog.image.src,
published: blog.published,
slug: blog.slug,
gitSha
};
await xata.db.blog.create(blogData);
}
};
export const syncBlogContentToXata = async () => {
try {
console.log('Syncing markdown blogs to Xata database');
await blogSync();
console.log('Blog content synced');
} catch (error) {
console.error('Blog content sync failed');
console.error(error);
}
};
export const docsSync = async () => {
const gitSha = process.env.NODE_ENV === 'development' ? 'development' : process.env.VERCEL_GIT_COMMIT_SHA;
const docsToDelete = await xata.db.docs.filter({ gitSha }).getAll();
for (const docToDelete of docsToDelete) {
console.log(`Deleting doc: ${docToDelete.slug}`);
await xata.db.docs.delete(docToDelete.id);
}
for (const doc of allDocs) {
// Headings and Keywords can be flattened into a string for search
const keywords = doc.keywords?.map((keyword) => keyword).join(' ') ?? '';
const headings = doc.headings?.map((heading: DocHeading) => heading.title).join(' ') ?? '';
const docData: Partial<XataDoc> = {
title: doc.title,
description: doc.description,
navTitle: doc.navTitle,
content: doc.body.raw,
published: doc.published,
slug: doc.slug,
keywords: keywords,
headings: headings,
gitSha
};
await xata.db.docs.create(docData);
}
};
export const syncDocsContentToXata = async () => {
try {
console.log('Syncing markdown docs to Xata database');
await docsSync();
console.log('Docs content synced');
} catch (error) {
console.error('Docs content sync failed');
console.error(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment