Skip to content

Commit

Permalink
test(katzencore): Checking out Storage Methods
Browse files Browse the repository at this point in the history
  • Loading branch information
maxlkatze committed Jul 22, 2024
1 parent 4753880 commit e2eeadf
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 65 deletions.
2 changes: 2 additions & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ export default defineNuxtConfig({
pages: true,
katzenCore: {
projectLocation: './playground',
secret: 'secret123',
projectName: 'playground',
},
})
59 changes: 31 additions & 28 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@ import {
extendPages,
installModule,
} from '@nuxt/kit'
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/fs'
import type { Storage } from 'unstorage'
import { defu } from 'defu'

import { type AzureAppConfigurationOptions } from 'unstorage/drivers/azure-app-configuration'
import { type KVOptions } from 'unstorage/drivers/cloudflare-kv-binding'
import { type FSStorageOptions } from 'unstorage/drivers/fs'
import { type GithubOptions } from 'unstorage/drivers/github'
import { type MongoDbOptions } from 'unstorage/drivers/mongodb'
import { type NetlifyStoreOptions } from 'unstorage/drivers/netlify-blobs'
import { type PlanetscaleDriverOptions } from 'unstorage/drivers/planetscale'
import { type RedisOptions } from 'unstorage/drivers/redis'
import { type VercelKVOptions } from 'unstorage/drivers/vercel-kv'
import pkg from '../package.json'
import { useContentStorage } from './runtime/storage/StorageManagment'

export interface CmsUser {
name: string
Expand All @@ -25,8 +31,12 @@ export interface CmsUser {
export interface ModuleOptions {
users: CmsUser[]
secret: string
projectName: string
projectLocation: string
storage?: Storage
storage: {
type: 'azure-app-configuration' | 'cloudflare-kv-binding' | 'fs' | 'github' | 'mongodb' | 'netlify-blobs' | 'planetscale' | 'redis' | 'vercel-kv'
options: AzureAppConfigurationOptions | KVOptions | FSStorageOptions | GithubOptions | MongoDbOptions | NetlifyStoreOptions | PlanetscaleDriverOptions | RedisOptions | VercelKVOptions
}
}

export default defineNuxtModule<ModuleOptions>({
Expand All @@ -43,19 +53,13 @@ export default defineNuxtModule<ModuleOptions>({
},
],
secret: 'secret',
projectName: 'defaultProject',
projectLocation: './',
},

hooks: {
'nitro:build:before': async (nuxt) => {
// load content from git storage
console.log('NITRO BUILD HOOK')
},
'vite:serverCreated': (viteServer, env) => {
console.log('VITE HOOK')
},
'nitro:build:public-assets': (nuxt) => {
console.log('NITRO BUILD PUBLIC')
storage: {
type: 'fs',
options: {
base: './',
},
},
},
async setup(_options, _nuxt) {
Expand All @@ -69,15 +73,6 @@ export default defineNuxtModule<ModuleOptions>({
},
)

if (!_options.storage) {
_options.storage = createStorage({
driver: fsDriver({ base: _options.projectLocation + '/' + 'public/' }),
})
}
const storage = _options.storage
// extend nuxt with storage as runtimeConfig does not work with objects


await installModules()
await addImports()

Expand Down Expand Up @@ -107,9 +102,17 @@ export default defineNuxtModule<ModuleOptions>({

_nuxt.options.runtimeConfig.users = _options.users
_nuxt.options.runtimeConfig.secret = _options.secret
_nuxt.options.runtimeConfig.storage = _options.storage
_nuxt.options.runtimeConfig.projectName = _options.projectName
_nuxt.options.runtimeConfig.projectLocation = _options.projectLocation + (_options.projectLocation.endsWith('/') ? '' : '/')
const content = await storage.getItem('content.katze.json')
console.log(content)
const storageKey = _options.projectName + '_katze_content'
_nuxt.options.runtimeConfig.storageKey = storageKey

const contentStorage = await useContentStorage(_nuxt.options.runtimeConfig)
let content = await contentStorage.getItem(storageKey)
if (content === null) {
content = {}
}
_nuxt.options.runtimeConfig.public.content = content
// console.info('Katze loaded ' + Object.entries(content).length + ' entries from content storage')

Expand Down
31 changes: 1 addition & 30 deletions src/runtime/composables/useUiComponents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,13 @@ import { ComponentType, useUiStore } from '../stores/UiStore'
import type { KatzenUIComponent, KatzenUIOptions } from '~/src/runtime/stores/UiStore'
import { useRuntimeConfig } from '#imports'

interface FetchedContentType {
content: Record<string, unknown>
}

export interface ImageContent {
src: string
alt: string
}

export const fetchedContent: FetchedContentType = { content: {} }

export const loadFetchContent = async () => {
interface ContentResponse {
body: {
content: Record<string, unknown>
}
}
const data = await $fetch<ContentResponse>('/content-cms', {
method: 'POST',
})
if (data === null) {
console.error('No content fetched')
return
}
fetchedContent.content = data.body.content

for (const key in fetchedContent.content) {
useUiStore().updateUiContent(key, fetchedContent.content[key])
}
}

export const getContent = () => {
if (Object.keys(fetchedContent.content).length === 0) {
return useRuntimeConfig().public.content as Record<string, unknown> || {}
}
return fetchedContent.content
return useRuntimeConfig().public.content as Record<string, unknown> || {}
}

export const getContentByKey = <T = string>(key: string) => {
Expand Down
3 changes: 0 additions & 3 deletions src/runtime/pages/KatzeCms.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<script setup lang="ts">
import MainView from '../components/views/MainView.vue'
import EditView from '../components/views/EditView.vue'
import { loadFetchContent } from '../composables/useUiComponents'
import { definePageMeta, ref, useCookie, useRouter } from '#imports'
definePageMeta({
Expand All @@ -11,8 +10,6 @@ definePageMeta({
const router = useRouter()
const currentView = ref<'MainView' | 'EditView'>('MainView')
loadFetchContent()
const logout = () => {
const tokenCookie = useCookie('token')
tokenCookie.value = ''
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/server/content.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/fs'
import { useAuthentication } from '../composables/useAuthentication'
import { useContentStorage } from '../storage/StorageManagment'
import { defineEventHandler, readBody, useRuntimeConfig } from '#imports'

export default defineEventHandler(async (event) => {
const runtimeConfig = useRuntimeConfig()
const storage = runtimeConfig.storage
console.log('storage', storage)
let savedContent = await storage.getItem('content.katze.json')
const storage = await useContentStorage(runtimeConfig)
let savedContent = await storage.getItem(runtimeConfig.storageKey)

const body = await readBody(event) || {}
const token = body.token || ''
Expand Down Expand Up @@ -38,7 +38,7 @@ export default defineEventHandler(async (event) => {
// add or replace content inside content
// merge data with content
savedContent = { ...savedContent as object, ...content }
await storage.setItem('content.katze.json', savedContent)
await storage.setItem(runtimeConfig.storageKey, savedContent)

return {
success: true,
Expand Down
31 changes: 31 additions & 0 deletions src/runtime/storage/StorageManagment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { createStorage, type Storage, type Driver } from 'unstorage'
import type { RuntimeConfig } from 'nuxt/schema'

interface StorageManagmentDriver extends Storage {
publishContent: (content: string) => Promise<void>
}

export const useContentStorage = async (runtimeConfig: RuntimeConfig): Promise<StorageManagmentDriver> => {
let driver: Driver
try {
driver = (await import(`unstorage/drivers/${runtimeConfig.storage.type}`))(runtimeConfig.storage.options)
}
catch (e) {
try {
driver = (await import(`unstorage/drivers/${runtimeConfig.storage.type}`)).default(JSON.parse(JSON.stringify(runtimeConfig.storage.options)))
}
catch (e) {
throw new Error(`Driver ${runtimeConfig.storage.type} not found`)
}
}

const storage = createStorage<object>({
driver,
}) as StorageManagmentDriver
// Add custom method to publish content
storage.publishContent = async (content) => {
// TODO
console.log('Publishing content', content)
}
return storage
}

0 comments on commit e2eeadf

Please sign in to comment.