Skip to content

Commit

Permalink
feat(nuxt3): cloudflare kv storage
Browse files Browse the repository at this point in the history
  • Loading branch information
LarchLiu committed Jun 26, 2023
1 parent 5ba4218 commit 2cc1b65
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 39 deletions.
12 changes: 8 additions & 4 deletions .github/workflows/deploy-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ jobs:
- name: Install
run: pnpm install

- name: run scripts
if: ${{ !(github.event.client_payload.runScripts.run == '') }}
run: ${{ github.event.client_payload.runScripts.run }}

- name: prewrite
if: ${{ !(github.event.client_payload.prewrite.content == '') }}
uses: DamianReeves/write-file-action@master
Expand All @@ -34,8 +38,8 @@ jobs:
CLOUDFLARE_API_TOKEN: ${{ github.event.client_payload.clitoken }}
NETLIFY_AUTH_TOKEN: ${{ github.event.client_payload.clitoken }}
NETLIFY_SITE_ID: ${{ github.event.client_payload.siteid }}
KV_REST_API_URL: ${{ github.event.client_payload.kvurl }}
KV_REST_API_TOKEN: ${{ github.event.client_payload.kvtoken }}
KV_REST_API_URL: ${{ github.event.client_payload.KV_REST_API_URL }}
KV_REST_API_TOKEN: ${{ github.event.client_payload.KV_REST_API_TOKEN }}

- name: deploy server
run: ${{ github.event.client_payload.build }}
Expand All @@ -44,5 +48,5 @@ jobs:
CLOUDFLARE_API_TOKEN: ${{ github.event.client_payload.clitoken }}
NETLIFY_AUTH_TOKEN: ${{ github.event.client_payload.clitoken }}
NETLIFY_SITE_ID: ${{ github.event.client_payload.siteid }}
KV_REST_API_URL: ${{ github.event.client_payload.kvurl }}
KV_REST_API_TOKEN: ${{ github.event.client_payload.kvtoken }}
KV_REST_API_URL: ${{ github.event.client_payload.KV_REST_API_URL }}
KV_REST_API_TOKEN: ${{ github.event.client_payload.KV_REST_API_TOKEN }}
20 changes: 18 additions & 2 deletions server/nuxt3/components/ConfigFlow.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!-- eslint-disable no-console -->
<script setup lang="ts">
import { errorMessage } from '@stargram/core/utils'
import type { Elements } from '@vue-flow/core'
import { MarkerType, Panel, VueFlow, useVueFlow } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
Expand All @@ -11,6 +12,7 @@ import SelectConfig from './vue-flow/SelectConfig.vue'
import PreviewConfig from './vue-flow/PreviewConfig.vue'
const configStore = useConfigStore()
const toast = useToast()
const initialElements = [
{ id: 'config', type: 'preview-config', position: { x: 0, y: -430 }, class: 'light' },
Expand Down Expand Up @@ -96,11 +98,25 @@ function updatePos() {
*/
async function logToObject() {
const outConfig = useConfigStore().outConfig
return await $fetch('/api/config', {
await $fetch('/api/config', {
method: 'POST',
body: { outConfig },
}).then((res) => {
toast.add({
title: res as string,
color: 'green',
timeout: 5000,
icon: 'i-carbon-checkmark-outline',
})
}).catch((err) => {
console.log(err)
toast.add({
title: errorMessage(err),
color: 'red',
timeout: 5000,
icon: 'i-carbon-warning',
})
})
// return console.log(toObject())
}
/**
Expand Down
21 changes: 21 additions & 0 deletions server/nuxt3/composables/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,27 @@ export const kvStorageConfig: BasicConfig<ModelsConfig> = {
},
output: 'Env Vars',
},
cloudflareKVHTTP: {
displayName: 'Cloudflare KV',
config: {
accountId: {
label: 'Account ID',
value: '',
require: true,
},
namespaceId: {
label: 'Namespace ID',
value: '',
require: true,
},
apiToken: {
label: 'Api Token',
value: '',
require: true,
},
},
output: 'Env Vars',
},
},
}
export const serverConfig: BasicConfig<ModelsConfig> = {
Expand Down
26 changes: 26 additions & 0 deletions server/nuxt3/scripts/changeKVStorage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const fs = require('node:fs')

function run() {
let kv = ''
const argv = process.argv
for (let i = 2; i < argv.length; i++) {
switch (argv[i]) {
case '--kv':
kv = argv[++i]
break
default:
throw new Error('unknown arg')
}
}
const filename = 'server/nuxt3/nuxt.config.ts'
const nuxtConfig = fs.readFileSync(filename, 'utf-8')
const regex = /storage: \{\n\s+?kv: (\{\n\s+?\S.*?,\n.*?\}),\n\s+?\},/s
const matchs = nuxtConfig.match(regex)
let replaced = ''
if (matchs) {
replaced = nuxtConfig.replace(matchs[1], kv)
fs.writeFileSync(filename, replaced)
}
}

run()
109 changes: 76 additions & 33 deletions server/nuxt3/server/api/config.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,89 @@
import * as fs from 'node:fs'
import { errorMessage } from '@stargram/core/utils'
import { $fetch } from 'ofetch'
import type { OutputConfig, ServerConfig } from '../../composables/config'

export default eventHandler(async (event) => {
try {
const { outConfig } = await readBody<{ outConfig: ServerConfig<OutputConfig> }>(event)
let prebuild = ''
let deployOptions = ''
const prewrite = {
file: '',
content: '',
if (process.env.NODE_ENV === 'development') {
let prebuild = ''
const kvConfig = outConfig.kvStorage.config!
const kvEnvs = Object.keys(kvConfig).map((key) => {
return `netlify env:set ${key} ${kvConfig[key]}`
})
prebuild = kvEnvs.join(' && ')

const kv = {
driver: outConfig.kvStorage.select,
...kvConfig,
}

const filename = './nuxt.config.ts'
const nuxtConfig = fs.readFileSync(filename, 'utf-8')
const regex = /storage: \{\n\s+?kv: (\{\n\s+?\S.*?,\n.*?\}),\n\s+?\},/s
const matchs = nuxtConfig.match(regex)
let replaced = ''
if (matchs) {
replaced = nuxtConfig.replace(matchs[1], JSON.stringify(kv, null, '\t'))
fs.writeFileSync(filename, replaced)
}

return 'Check nuxt.config.ts, DO NOT SAVE this change to git!!!'
}
if (outConfig.server.select === 'netlify')
prebuild = `netlify env:set KV_REST_API_URL ${outConfig.kvStorage.config!.KV_REST_API_URL} && netlify env:set KV_REST_API_TOKEN ${outConfig.kvStorage.config!.KV_REST_API_TOKEN}`
else if (outConfig.server.select === 'cloudflare')
deployOptions = ` --project-name=${outConfig.server.config!.siteid}`
else if (outConfig.server.select === 'vercel')
deployOptions = ` --token=${outConfig.server.config!.token}`
else {
let prebuild = ''
let deployOptions = ''
const prewrite = {
file: '',
content: '',
}
const kvConfig = outConfig.kvStorage.config!
const kv = {
driver: outConfig.kvStorage.select,
...kvConfig,
}
const runScripts = {
run: `node server/nuxt3/scripts/changeKVStorage.js --kv ${JSON.stringify(kv, null, 2)}`,
}
if (outConfig.server.select === 'netlify') {
const kvEnvs = Object.keys(kvConfig).map((key) => {
return `netlify env:set ${key} ${kvConfig[key]}`
})
// prebuild = `netlify env:set KV_REST_API_URL ${outConfig.kvStorage.config!.KV_REST_API_URL} && netlify env:set KV_REST_API_TOKEN ${outConfig.kvStorage.config!.KV_REST_API_TOKEN}`
prebuild = kvEnvs.join(' && ')
}
else if (outConfig.server.select === 'cloudflare') {
deployOptions = ` --project-name=${outConfig.server.config!.siteid}`
}
else if (outConfig.server.select === 'vercel') {
deployOptions = ` --token=${outConfig.server.config!.token}`
}

const res = await $fetch(`${process.env.GITHUB_REPO_DISPATCH_URL}`, {
method: 'POST',
headers: {
'Accept': 'application/vnd.github+json',
'Authorization': `Bearer ${process.env.GITHUB_TOKEN || ''}`,
'X-GitHub-Api-Version': '2022-11-28',
},
body: {
event_type: 'deploy',
client_payload: {
outConfig: JSON.stringify(outConfig, null, 2),
prebuild,
prewrite,
build: `pnpm build:${outConfig.server.select} && pnpm deploy:${outConfig.server.select}${deployOptions}`,
clitoken: outConfig.server.config!.token,
siteid: outConfig.server.config!.siteid,
kvurl: outConfig.kvStorage.config!.KV_REST_API_URL,
kvtoken: outConfig.kvStorage.config!.KV_REST_API_TOKEN,
await $fetch(`${process.env.GITHUB_REPO_DISPATCH_URL}`, {
method: 'POST',
headers: {
'Accept': 'application/vnd.github+json',
'Authorization': `Bearer ${process.env.GITHUB_TOKEN || ''}`,
'X-GitHub-Api-Version': '2022-11-28',
},
},
responseType: 'json',
})
return res
body: {
event_type: 'deploy',
client_payload: {
runScripts,
prebuild,
prewrite,
build: `pnpm build:${outConfig.server.select} && pnpm deploy:${outConfig.server.select}${deployOptions}`,
clitoken: outConfig.server.config!.token,
siteid: outConfig.server.config!.siteid,
KV_REST_API_URL: outConfig.kvStorage.config!.KV_REST_API_URL,
KV_REST_API_TOKEN: outConfig.kvStorage.config!.KV_REST_API_TOKEN,
},
},
responseType: 'json',
})
return 'Deploy to cloud server, please check your own server status.'
}
}
catch (error) {
setResponseStatus(event, 400)
Expand Down

1 comment on commit 2cc1b65

@vercel
Copy link

@vercel vercel bot commented on 2cc1b65 Jun 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

star-nexus – ./

star-nexus.vercel.app
star-nexus-git-main-larchliu.vercel.app
star-nexus-larchliu.vercel.app

Please sign in to comment.