Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
atinux committed Jan 24, 2024
1 parent 6678a6e commit a41546f
Show file tree
Hide file tree
Showing 12 changed files with 253 additions and 50 deletions.
10 changes: 6 additions & 4 deletions _nuxtflare/server/utils/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ofetch } from 'ofetch'
import Database from 'better-sqlite3'
import { join } from 'pathe'

// export * as tables from '~/server/database/schema'
export * as tables from '~/server/database/schema'

let _db: DrizzleD1Database | BetterSQLite3Database | SqliteRemoteDatabase | null = null
let _client: any = null
Expand All @@ -30,11 +30,13 @@ export const useDatabase = () => {
method: 'POST',
body: { sql, params, method }
})
console.log(method, rows)
if (method === 'run') return rows
return { rows }
} catch (err) {
console.error('Error from remote database', { sql, params, method }, err.data)
} catch (err: any) {
if (['begin', 'commit'].includes(sql)) {
return { rows: [] }
}
console.error('Error from remote database:', err.data.message, '\n', { sql, params, method })
return { rows: [] }
}
})
Expand Down
20 changes: 18 additions & 2 deletions app.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
export default defineAppConfig({
ui: {
primary: 'lime',
gray: 'neutral'
primary: 'emerald',
container: {
constrained: 'max-w-2xl'
},
card: {
header: {
base: 'flex flex-wrap items-center justify-between'
},
body: {
base: 'space-y-4'
}
},
dropdown: {
width: 'w-full',
popper: {
strategy: 'absolute'
}
}
}
})
81 changes: 60 additions & 21 deletions app.vue
Original file line number Diff line number Diff line change
@@ -1,31 +1,70 @@
<script setup lang="ts">
<script setup>
const { loggedIn } = useUserSession()
const colorMode = useColorMode()
const color = computed(() => colorMode.value === 'dark' ? '#111827' : 'white')
watch(loggedIn, () => {
if (!loggedIn.value) {
navigateTo('/')
}
})
function toggleColorMode() {
colorMode.preference = colorMode.preference === 'dark' ? 'light' : 'dark'
}
useHead({
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ key: 'theme-color', name: 'theme-color', content: color }
],
link: [
{ rel: 'icon', href: '/favicon.ico' }
],
htmlAttrs: {
lang: 'en'
}
htmlAttrs: { lang: 'en' },
link: [{ rel: 'icon', href: '/icon.png' }],
})
useSeoMeta({
viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
title: 'Nuxt Todos Edge',
description:
'A Nuxt demo hosted with Edge-side rendering, authentication and queyring a SQLite database',
ogImage: '/social-image.png',
twitterImage: '/social-image.png',
twitterCard: 'summary_large_image',
})
</script>

<template>
<div>
<NuxtLoadingIndicator />
<UContainer class="min-h-screen flex flex-col justify-center">
<div class="mb-2 text-right">
<UButton
square
variant="ghost"
color="black"
:icon="$colorMode.preference === 'dark' ? 'i-heroicons-moon' : 'i-heroicons-sun'"
@click="toggleColorMode"
/>
</div>

<NuxtPage />

<NuxtLayout>
<NuxtPage />
</NuxtLayout>
<footer class="text-center mt-2">
<NuxtLink
href="https://github.com/atinux/nuxt-todos-edge"
target="_blank"
class="text-sm text-gray-500 hover:text-gray-700"
>
GitHub
</NuxtLink>
·
<NuxtLink
href="https://twitter.com/Atinux"
target="_blank"
class="text-sm text-gray-500 hover:text-gray-700"
>
Twitter
</NuxtLink>
</footer>
</UContainer>
<UNotifications />
</template>

<UNotifications />
</div>
</template>
<style lang="postcss">
body {
@apply font-sans text-gray-950 bg-gray-50 dark:bg-gray-950 dark:text-gray-50;
}
</style>
2 changes: 1 addition & 1 deletion nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export default defineNuxtConfig({
devtools: { enabled: true },
// extends: '@nuxt/ui-pro',
extends: [
'/Users/atinux/Projects/nuxt/ui-pro',
// '/Users/atinux/Projects/nuxt/ui-pro',
'./_nuxtflare'
],
modules: [
Expand Down
117 changes: 117 additions & 0 deletions pages/todos.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<script setup>
definePageMeta({
middleware: 'auth'
})
const loading = ref(false)
const newTodo = ref('')
const newTodoInput = ref(null)
const toast = useToast()
const { user, clear } = useUserSession()
const { data: todos } = await useFetch('/api/todos')
async function addTodo () {
if (!newTodo.value.trim()) { return }
loading.value = true
try {
const todo = await $fetch('/api/todos', {
method: 'POST',
body: {
title: newTodo.value,
completed: 0
}
})
todos.value.push(todo)
toast.add({ title: `Todo "${todo.title}" created.` })
newTodo.value = ''
nextTick(() => {
newTodoInput.value?.input?.focus()
})
} catch (err) {
if (err.data?.data?.issues) {
const title = err.data.data.issues.map(issue => issue.message).join('\n')
toast.add({ title, color: 'red' })
}
}
loading.value = false
}
async function toggleTodo (todo) {
todo.completed = Number(!todo.completed)
await useFetch(`/api/todos/${todo.id}`, {
method: 'PATCH',
body: {
completed: todo.completed
}
})
}
async function deleteTodo (todo) {
await useFetch(`/api/todos/${todo.id}`, { method: 'DELETE' })
todos.value = todos.value.filter(t => t.id !== todo.id)
toast.add({ title: `Todo "${todo.title}" deleted.` })
}
const items = [[{
label: 'Logout',
icon: 'i-heroicons-arrow-left-on-rectangle',
click: clear
}]]
</script>
<template>
<UCard @submit.prevent="addTodo">
<template #header>
<h3 class="text-lg font-semibold leading-6">
<NuxtLink to="/">
Todo List
</NuxtLink>
</h3>
<UDropdown v-if="user" :items="items">
<UButton color="white" trailing-icon="i-heroicons-chevron-down-20-solid">
<UAvatar :src="`https://github.com/${user.login}.png`" :alt="user.login" size="3xs" />
{{ user.login }}
</UButton>
</UDropdown>
</template>
<div class="flex items-center gap-2">
<UInput
ref="newTodoInput"
v-model="newTodo"
name="todo"
:disabled="loading"
class="flex-1"
placeholder="Make a Nuxt demo"
autocomplete="off"
autofocus
:ui="{ wrapper: 'flex-1' }"
/>
<UButton type="submit" icon="i-heroicons-plus-20-solid" :loading="loading" :disabled="newTodo.trim().length === 0" />
</div>
<ul class="divide-y divide-gray-200 dark:divide-gray-800">
<li
v-for="todo of todos"
:key="todo.id"
class="flex items-center gap-4 py-2"
>
<span class="flex-1 font-medium" :class="[todo.completed ? 'line-through text-gray-500' : '']">{{ todo.title }}</span>
<UToggle :model-value="Boolean(todo.completed)" @update:model-value="toggleTodo(todo)" />
<UButton
color="red"
variant="soft"
size="2xs"
icon="i-heroicons-x-mark-20-solid"
@click="deleteTodo(todo)"
/>
</li>
</ul>
</UCard>
</template>
21 changes: 11 additions & 10 deletions server/api/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export default defineEventHandler(async (event) => {

const tables = await db.all(sql`
SELECT
name
name,
type
FROM
sqlite_schema
WHERE
Expand All @@ -19,18 +20,18 @@ export default defineEventHandler(async (event) => {
id: integer('id').primaryKey(),
text: text('text')
})
const inserted = await db.insert(todos).values({ text: 'hello' }).returning().get()
const todo = await db.select().from(todos).where(eq(todos.id, inserted.id)).get()
const updated = await db.update(todos).set({ text: 'Bonjour' }).where(eq(todos.id, inserted.id)).returning()
// const inserted = await db.insert(todos).values({ text: 'hello' }).returning().get()
// const todo = await db.select().from(todos).where(eq(todos.id, inserted.id)).get()
// const updated = await db.update(todos).set({ text: 'Bonjour' }).where(eq(todos.id, inserted.id)).returning()
const all = await db.select().from(todos).limit(3)
const deleted = await db.delete(todos).where(eq(todos.id, all[0].id))
// const deleted = await db.delete(todos).where(eq(todos.id, all[0].id))

return {
tables,
todo,
inserted,
updated,
deleted,
// tables,
// todo,
// inserted,
// updated,
// deleted,
all
}
})
7 changes: 7 additions & 0 deletions server/database/migrations/0000_good_jackpot.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE `todos` (
`id` integer PRIMARY KEY NOT NULL,
`user_id` integer NOT NULL,
`title` text NOT NULL,
`completed` integer DEFAULT 0 NOT NULL,
`created_at` integer NOT NULL
);
4 changes: 0 additions & 4 deletions server/database/migrations/0000_swift_stone_men.sql

This file was deleted.

28 changes: 25 additions & 3 deletions server/database/migrations/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"version": "5",
"dialect": "sqlite",
"id": "6d6fc5db-ed1d-4e06-bfbd-6b8a014b0b00",
"id": "4f710177-2751-43af-9d16-88ac9acdbc35",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"todos": {
Expand All @@ -14,12 +14,34 @@
"notNull": true,
"autoincrement": false
},
"text": {
"name": "text",
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"completed": {
"name": "completed",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
Expand Down
4 changes: 2 additions & 2 deletions server/database/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
{
"idx": 0,
"version": "5",
"when": 1706118044364,
"tag": "0000_swift_stone_men",
"when": 1706120994243,
"tag": "0000_good_jackpot",
"breakpoints": true
}
]
Expand Down
7 changes: 5 additions & 2 deletions server/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,8 @@ import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'

export const todos = sqliteTable('todos', {
id: integer('id').primaryKey(),
text: text('text').notNull(),
})
userId: integer('user_id').notNull(), // GitHub Id
title: text('title').notNull(),
completed: integer('completed').notNull().default(0),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull(),
})
Loading

0 comments on commit a41546f

Please sign in to comment.