Created
July 16, 2024 19:29
-
-
Save ManUtopiK/84580cd8fd9e135eb5d5e1901403a4d4 to your computer and use it in GitHub Desktop.
Gitlab webhook to refresh nuxt-content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { defineEventHandler, getRequestHeader, readBody } from 'h3' | |
import { transformContent } from '@nuxt/content/transformers' | |
// @ts-expect-error Missing imports | |
import { useStorage, useRuntimeConfig } from '#imports' | |
export default defineEventHandler(async (event) => { | |
const secret = getRequestHeader(event, 'X-Gitlab-Token') | |
const body = await readBody(event) | |
const commits = body.commits | |
const config = useRuntimeConfig() | |
// const web_url = body.project.web_url | |
if (!commits?.length) return { status: 'done: no commit' } | |
const storage = useStorage() | |
const setParsedItem = async (file: string, currentContent: string) => { | |
const { repo, branch, base } = config.content.sources.content | |
const content = await $fetch( | |
`/api/v4/projects/${encodeURIComponent(repo)}/repository/files/${encodeURIComponent(file)}/raw`, | |
{ | |
baseURL: 'https://gitlab.com', | |
// headers: opts.getHeaders ? await opts.getHeaders() : undefined, | |
query: { ref: branch }, | |
}, | |
) | |
// const content = await storage.getItem(key) // Don't work in production mode | |
const key = file.replace('/', ':') | |
const parsed = await transformContent(key, content || '') | |
// Merge hash of previous generated content | |
const bodyItem = { parsed, hash: (await storage.getItem('cache:content:parsed:' + key))?.hash } | |
// Set the new content | |
await storage.setItem('cache:content:parsed:' + key, bodyItem) | |
await storage.setItem('assets:nitro:bundled:cache:content:parsed:' + key, bodyItem) | |
} | |
// Collect all added, modified and removed files from all commits | |
const added = [] | |
const modified = [] | |
const removed = [] | |
for (const commit of commits) { | |
added.push(...commit.added) | |
modified.push(...commit.modified) | |
removed.push(...commit.removed) | |
} | |
const currentContent = 'content:source:content' | |
// Force refetch from gitlab ? | |
// const keys = await storage.getKeys('content:source:content:', { force: true }) | |
// Remove duplicates | |
const merged = [...new Set([...added, ...modified])].filter(file => file.startsWith('content') || file.startsWith('public')) | |
for (const file of merged) { | |
await setParsedItem(file, currentContent) | |
} | |
for (const file of [...new Set(removed)]) { | |
await storage.removeItem(file.replace(currentContent, 'cache:content:parsed:content')) | |
} | |
return { | |
status: 'done', | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment