create-knit 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +17 -2
- package/index.mjs +248 -0
- package/package.json +32 -3
- package/template/base/.claude/skills/knit-add-api/SKILL.md +41 -0
- package/template/base/.claude/skills/knit-add-model/SKILL.md +31 -0
- package/template/base/.cursor/mcp.json +24 -0
- package/template/base/.mcp.json +25 -0
- package/template/base/.vscode/mcp.json +25 -0
- package/template/base/AGENTS.md +76 -0
- package/template/base/CLAUDE.md +9 -0
- package/template/base/_gitignore +13 -0
- package/template/base/apps/web/.env.example +124 -0
- package/template/base/apps/web/app/app.vue +7 -0
- package/template/base/apps/web/app/pages/index.vue +20 -0
- package/template/base/apps/web/tsconfig.json +9 -0
- package/template/base/docker/.env.production.example +21 -0
- package/template/base/docker/Dockerfile +64 -0
- package/template/base/docker/Dockerfile.dockerignore +16 -0
- package/template/base/docker/dev.Dockerfile +10 -0
- package/template/base/docker/dev.Dockerfile.dockerignore +2 -0
- package/template/base/docker/docker-compose.prod.yml +44 -0
- package/template/base/docker-compose.yml +71 -0
- package/template/examples/apps/web/app/pages/platform.vue +94 -0
- package/template/examples/apps/web/server/api/demo/flash.post.ts +5 -0
- package/template/examples/layers/example-blog/admin.ts +126 -0
- package/template/examples/layers/example-blog/app/pages/blog/[slug].vue +169 -0
- package/template/examples/layers/example-blog/app/pages/blog/index.vue +73 -0
- package/template/examples/layers/example-blog/app/pages/blog/stats.vue +33 -0
- package/template/examples/layers/example-blog/commands/publishpost.ts +23 -0
- package/template/examples/layers/example-blog/i18n/locales/de.json +140 -0
- package/template/examples/layers/example-blog/i18n/locales/en.json +33 -0
- package/template/examples/layers/example-blog/i18n/locales/es.json +140 -0
- package/template/examples/layers/example-blog/nuxt.config.ts +9 -0
- package/template/examples/layers/example-blog/package.json +18 -0
- package/template/examples/layers/example-blog/server/api/blog/posts/[slug].get.ts +15 -0
- package/template/examples/layers/example-blog/server/api/blog/posts.get.ts +14 -0
- package/template/examples/layers/example-blog/server/api/blog/word-count.post.ts +23 -0
- package/template/examples/layers/example-blog/server/channels/comments.ts +39 -0
- package/template/examples/layers/example-blog/server/database/schema.ts +160 -0
- package/template/examples/layers/example-blog/server/database/seed.ts +24 -0
- package/template/examples/layers/example-blog/server/feeds/blog.ts +26 -0
- package/template/examples/layers/example-blog/server/resources/comments.ts +78 -0
- package/template/examples/layers/example-blog/server/resources/posts.ts +25 -0
- package/template/examples/layers/example-blog/server/routes/blog/atom.xml.ts +4 -0
- package/template/examples/layers/example-blog/server/routes/blog/feed.xml.ts +4 -0
- package/template/examples/layers/example-blog/server/sitemaps/blog.ts +14 -0
- package/template/examples/layers/example-blog/server/tasks/blog.ts +49 -0
- package/template/examples/layers/example-blog/test/blog.test.ts +46 -0
- package/template/examples/layers/example-blog/test/i18n.test.ts +27 -0
- package/template/examples/layers/example-blog/tsconfig.json +9 -0
- package/template/examples/layers/example-dashboard/app/pages/dashboard.vue +67 -0
- package/template/examples/layers/example-dashboard/i18n/locales/de.json +12 -0
- package/template/examples/layers/example-dashboard/i18n/locales/en.json +12 -0
- package/template/examples/layers/example-dashboard/i18n/locales/es.json +12 -0
- package/template/examples/layers/example-dashboard/nuxt.config.ts +12 -0
- package/template/examples/layers/example-dashboard/package.json +16 -0
- package/template/examples/layers/example-dashboard/tsconfig.json +9 -0
- package/template/versions.json +13 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `POST { postId }`: enqueues the `blog.word-count` task and flashes the outcome (a toast on the
|
|
3
|
+
* next page, or right away via `useFlash().check()`). With the immediate backend the result is ready now.
|
|
4
|
+
*/
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
await requireAuth(event)
|
|
7
|
+
const body = await readBody<{ postId?: unknown }>(event)
|
|
8
|
+
const postId = Number(body?.postId)
|
|
9
|
+
if (!Number.isInteger(postId) || postId < 1) throw createError({ statusCode: 400, statusMessage: 'Expected { postId: number }' })
|
|
10
|
+
|
|
11
|
+
const task = await enqueue('blog.word-count', { postId })
|
|
12
|
+
if (task.status === 'succeeded') {
|
|
13
|
+
const { words, title } = task.result as { words: number, title: string }
|
|
14
|
+
flash(event, { type: 'success', title: `${intcomma(words)} word${pluralize(words)}`, description: `in “${title}”` })
|
|
15
|
+
}
|
|
16
|
+
else if (task.status === 'failed') {
|
|
17
|
+
flash(event, { type: 'error', title: 'Word count failed', description: task.error?.split('\n')[0] })
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
flash(event, { type: 'info', title: 'Word count queued', description: `Task ${task.id}` })
|
|
21
|
+
}
|
|
22
|
+
return task
|
|
23
|
+
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live comments for one post (Django Channels: a consumer joined to a group per post).
|
|
3
|
+
* `server/database/schema.ts` broadcasts comment writes here with `broadcastModel`.
|
|
4
|
+
*
|
|
5
|
+
* Anyone may listen, but moderation still applies to what each subscriber receives:
|
|
6
|
+
* - moderators (`blog.change_comment`) get every event;
|
|
7
|
+
* - authors get events about their own pending comments;
|
|
8
|
+
* - everyone else only hears about approved comments. A comment that is unapproved again reaches
|
|
9
|
+
* them as `deleted` (just its id), so it disappears from their page too.
|
|
10
|
+
*/
|
|
11
|
+
import { defineChannel } from '@knit-framework/core/realtime'
|
|
12
|
+
|
|
13
|
+
const MODERATE = 'blog.change_comment'
|
|
14
|
+
|
|
15
|
+
interface CommentEvent {
|
|
16
|
+
id: number
|
|
17
|
+
authorId: string
|
|
18
|
+
approved: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isCommentEvent(value: unknown): value is CommentEvent {
|
|
22
|
+
if (typeof value !== 'object' || value === null) return false
|
|
23
|
+
const v = value as Record<string, unknown>
|
|
24
|
+
return typeof v.id === 'number' && typeof v.authorId === 'string' && typeof v.approved === 'boolean'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const postComments = defineChannel('comments:post:{id}', {
|
|
28
|
+
description: 'Comment created/updated/deleted events for one post',
|
|
29
|
+
authorize: ctx => /^\d+$/.test(ctx.params.id ?? ''),
|
|
30
|
+
filter(message, ctx) {
|
|
31
|
+
if (ctx.can(MODERATE)) return true
|
|
32
|
+
if (!isCommentEvent(message.data)) return false
|
|
33
|
+
const comment = message.data
|
|
34
|
+
if (comment.approved || (ctx.user && comment.authorId === ctx.user.id)) return true
|
|
35
|
+
// Never seen by this visitor while pending: nothing to announce.
|
|
36
|
+
if (message.event === 'created') return false
|
|
37
|
+
return { event: 'deleted', data: { id: comment.id } }
|
|
38
|
+
},
|
|
39
|
+
})
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { relations } from 'drizzle-orm'
|
|
2
|
+
import { boolean, index, integer, pgTable, serial, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core'
|
|
3
|
+
import { fileColumn } from '@knit-framework/core/fields'
|
|
4
|
+
import { defineModelMeta, signals, ValidationError } from '@knit-framework/core/models'
|
|
5
|
+
import { broadcastModel } from '@knit-framework/core/realtime'
|
|
6
|
+
import { user } from '@knit-framework/core/schema'
|
|
7
|
+
|
|
8
|
+
export const category = pgTable('blog_category', {
|
|
9
|
+
id: serial('id').primaryKey(),
|
|
10
|
+
name: varchar('name', { length: 120 }).notNull(),
|
|
11
|
+
slug: varchar('slug', { length: 140 }).notNull().unique(),
|
|
12
|
+
description: text('description'),
|
|
13
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
export const post = pgTable(
|
|
17
|
+
'blog_post',
|
|
18
|
+
{
|
|
19
|
+
id: serial('id').primaryKey(),
|
|
20
|
+
title: varchar('title', { length: 200 }).notNull(),
|
|
21
|
+
slug: varchar('slug', { length: 220 }).notNull().unique(),
|
|
22
|
+
body: text('body').notNull().default(''),
|
|
23
|
+
/** Optional cover image (Django: `ImageField`); the admin shows an upload widget. */
|
|
24
|
+
cover: fileColumn('cover'),
|
|
25
|
+
published: boolean('published').notNull().default(false),
|
|
26
|
+
publishedAt: timestamp('published_at', { withTimezone: true }),
|
|
27
|
+
categoryId: integer('category_id').references(() => category.id, { onDelete: 'set null' }),
|
|
28
|
+
authorId: text('author_id').references(() => user.id, { onDelete: 'set null' }),
|
|
29
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
30
|
+
updatedAt: timestamp('updated_at', { withTimezone: true })
|
|
31
|
+
.notNull()
|
|
32
|
+
.defaultNow()
|
|
33
|
+
.$onUpdate(() => new Date()),
|
|
34
|
+
},
|
|
35
|
+
t => [index('blog_post_category_id_idx').on(t.categoryId)],
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
export const tag = pgTable('blog_tag', {
|
|
39
|
+
id: serial('id').primaryKey(),
|
|
40
|
+
name: varchar('name', { length: 60 }).notNull().unique(),
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/** Many-to-many join table between posts and tags (edited from the post's change form). */
|
|
44
|
+
export const postTag = pgTable(
|
|
45
|
+
'blog_post_tag',
|
|
46
|
+
{
|
|
47
|
+
id: serial('id').primaryKey(),
|
|
48
|
+
postId: integer('post_id').notNull().references(() => post.id, { onDelete: 'cascade' }),
|
|
49
|
+
tagId: integer('tag_id').notNull().references(() => tag.id, { onDelete: 'cascade' }),
|
|
50
|
+
},
|
|
51
|
+
t => [uniqueIndex('blog_post_tag_post_tag_idx').on(t.postId, t.tagId)],
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Reader comments (Django: a `Comment` model with `ForeignKey`s to the post and the user).
|
|
56
|
+
* Exposed publicly by `server/resources/comments.ts`; moderated in the admin.
|
|
57
|
+
*/
|
|
58
|
+
export const comment = pgTable(
|
|
59
|
+
'blog_comment',
|
|
60
|
+
{
|
|
61
|
+
id: serial('id').primaryKey(),
|
|
62
|
+
postId: integer('post_id').notNull().references(() => post.id, { onDelete: 'cascade' }),
|
|
63
|
+
authorId: text('author_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
|
|
64
|
+
body: text('body').notNull(),
|
|
65
|
+
approved: boolean('approved').notNull().default(false),
|
|
66
|
+
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
67
|
+
updatedAt: timestamp('updated_at', { withTimezone: true })
|
|
68
|
+
.notNull()
|
|
69
|
+
.defaultNow()
|
|
70
|
+
.$onUpdate(() => new Date()),
|
|
71
|
+
},
|
|
72
|
+
t => [index('blog_comment_post_id_idx').on(t.postId)],
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
export const commentRelations = relations(comment, ({ one }) => ({
|
|
76
|
+
post: one(post, { fields: [comment.postId], references: [post.id] }),
|
|
77
|
+
author: one(user, { fields: [comment.authorId], references: [user.id] }),
|
|
78
|
+
}))
|
|
79
|
+
|
|
80
|
+
export const tagRelations = relations(tag, ({ many }) => ({
|
|
81
|
+
posts: many(postTag),
|
|
82
|
+
}))
|
|
83
|
+
|
|
84
|
+
export const postTagRelations = relations(postTag, ({ one }) => ({
|
|
85
|
+
post: one(post, { fields: [postTag.postId], references: [post.id] }),
|
|
86
|
+
tag: one(tag, { fields: [postTag.tagId], references: [tag.id] }),
|
|
87
|
+
}))
|
|
88
|
+
|
|
89
|
+
export const categoryRelations = relations(category, ({ many }) => ({
|
|
90
|
+
posts: many(post),
|
|
91
|
+
}))
|
|
92
|
+
|
|
93
|
+
export const postRelations = relations(post, ({ one, many }) => ({
|
|
94
|
+
tags: many(postTag),
|
|
95
|
+
comments: many(comment),
|
|
96
|
+
category: one(category, { fields: [post.categoryId], references: [category.id] }),
|
|
97
|
+
author: one(user, { fields: [post.authorId], references: [user.id] }),
|
|
98
|
+
}))
|
|
99
|
+
|
|
100
|
+
// Model options and validation (Django: `class Meta`, field validators, `Model.clean()`).
|
|
101
|
+
// They live next to the tables because both the server and `pnpm manage` load this file.
|
|
102
|
+
// Enforced by `useModel(table)` on every create/update.
|
|
103
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
104
|
+
const slugValidator = (value: string | undefined): string | undefined =>
|
|
105
|
+
value !== undefined && !SLUG_RE.test(value) ? 'Use lowercase letters, numbers and hyphens only.' : undefined
|
|
106
|
+
|
|
107
|
+
defineModelMeta(category, {
|
|
108
|
+
verboseName: 'category',
|
|
109
|
+
verboseNamePlural: 'categories',
|
|
110
|
+
ordering: ['name'],
|
|
111
|
+
validators: { slug: [slugValidator] },
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
defineModelMeta(post, {
|
|
115
|
+
ordering: ['-createdAt'],
|
|
116
|
+
validators: {
|
|
117
|
+
slug: [slugValidator],
|
|
118
|
+
title: [value => (value !== undefined && value.trim().length < 3 ? 'At least 3 characters.' : undefined)],
|
|
119
|
+
},
|
|
120
|
+
clean(row) {
|
|
121
|
+
if (row.published && !row.body?.trim()) {
|
|
122
|
+
throw new ValidationError({ body: 'A published post needs a body.' })
|
|
123
|
+
}
|
|
124
|
+
// Stamp the publication date the first time a post is published.
|
|
125
|
+
if (row.published && !row.publishedAt) return { publishedAt: new Date() }
|
|
126
|
+
},
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
defineModelMeta(comment, {
|
|
130
|
+
ordering: ['createdAt'],
|
|
131
|
+
validators: {
|
|
132
|
+
body: [(value) => {
|
|
133
|
+
const length = value?.trim().length ?? 0
|
|
134
|
+
if (value !== undefined && length < 2) return 'Write at least 2 characters.'
|
|
135
|
+
if (length > 2000) return 'Keep it under 2000 characters.'
|
|
136
|
+
}],
|
|
137
|
+
},
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
// Signals (Django: pre_save). Receivers run inside the write's transaction.
|
|
141
|
+
signals.preSave.connect(post, ({ instance }) => {
|
|
142
|
+
if (typeof instance.title === 'string') instance.title = instance.title.trim()
|
|
143
|
+
})
|
|
144
|
+
signals.preSave.connect(comment, ({ instance }) => {
|
|
145
|
+
if (typeof instance.body === 'string') instance.body = instance.body.trim()
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
// Realtime (Django Channels: a post_save receiver calling `group_send`): every comment write
|
|
149
|
+
// through useModel (the site, the admin's "Approve selected", tasks) is published, after commit,
|
|
150
|
+
// on `comments:post:<id>`. Who receives what is decided by `server/channels/comments.ts`.
|
|
151
|
+
broadcastModel(comment, {
|
|
152
|
+
channel: row => `comments:post:${row.postId}`,
|
|
153
|
+
// Ids only: the page re-reads the list through the `comments` resource, which applies moderation.
|
|
154
|
+
serialize: row => ({ id: row.id, postId: row.postId, authorId: row.authorId, approved: row.approved }),
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
export type Category = typeof category.$inferSelect
|
|
158
|
+
export type Post = typeof post.$inferSelect
|
|
159
|
+
export type Tag = typeof tag.$inferSelect
|
|
160
|
+
export type Comment = typeof comment.$inferSelect
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Demo content for `pnpm manage seed`. Idempotent: existing slugs are left alone.
|
|
3
|
+
*/
|
|
4
|
+
import { defineSeed } from '@knit-framework/core/commands'
|
|
5
|
+
import { useModel } from '@knit-framework/core/models'
|
|
6
|
+
import { category, post } from './schema'
|
|
7
|
+
|
|
8
|
+
export default defineSeed(async ({ db }) => {
|
|
9
|
+
const categories = useModel(category, { db })
|
|
10
|
+
const posts = useModel(post, { db })
|
|
11
|
+
|
|
12
|
+
const news = await categories.first({ where: { slug: 'news' } })
|
|
13
|
+
?? await categories.create({ name: 'News', slug: 'news', description: 'Announcements and updates.' })
|
|
14
|
+
|
|
15
|
+
const drafts = [
|
|
16
|
+
{ title: 'Hello, Knit', slug: 'hello-knit', body: 'Our first post, created by the seed.', published: true },
|
|
17
|
+
{ title: 'Working with models', slug: 'working-with-models', body: 'useModel() validates every write.', published: false },
|
|
18
|
+
]
|
|
19
|
+
for (const draft of drafts) {
|
|
20
|
+
if (await posts.exists({ slug: draft.slug })) continue
|
|
21
|
+
await posts.create({ ...draft, categoryId: news.id })
|
|
22
|
+
}
|
|
23
|
+
console.log(` ${await categories.count()} categories, ${await posts.count()} posts`)
|
|
24
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { desc, eq } from 'drizzle-orm'
|
|
2
|
+
|
|
3
|
+
/** Shared by the RSS (`/blog/feed.xml`) and Atom (`/blog/atom.xml`) routes. */
|
|
4
|
+
export const blogFeed = {
|
|
5
|
+
title: 'Knit blog',
|
|
6
|
+
link: '/blog',
|
|
7
|
+
description: 'Latest posts from the example blog.',
|
|
8
|
+
language: 'en',
|
|
9
|
+
async items() {
|
|
10
|
+
const posts = await useDB().query.post.findMany({
|
|
11
|
+
where: eq(tables.post.published, true),
|
|
12
|
+
orderBy: desc(tables.post.publishedAt),
|
|
13
|
+
limit: 20,
|
|
14
|
+
with: { author: { columns: { name: true } }, category: { columns: { name: true } } },
|
|
15
|
+
})
|
|
16
|
+
return posts.map(p => ({
|
|
17
|
+
title: p.title,
|
|
18
|
+
link: `/blog/${p.slug}`,
|
|
19
|
+
description: truncatewords(p.body, 50),
|
|
20
|
+
date: p.publishedAt ?? p.createdAt,
|
|
21
|
+
updated: p.updatedAt,
|
|
22
|
+
author: p.author?.name,
|
|
23
|
+
categories: p.category ? [p.category.name] : [],
|
|
24
|
+
}))
|
|
25
|
+
},
|
|
26
|
+
} satisfies Parameters<typeof defineFeed>[0]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public comments API (DRF: `ModelViewSet` + `IsAuthenticatedOrReadOnly` + an "is owner"
|
|
3
|
+
* object permission + `perform_create`), served at `/api/r/comments`.
|
|
4
|
+
*
|
|
5
|
+
* - Anyone lists approved comments: `GET /api/r/comments?postId=3`.
|
|
6
|
+
* - Signed-in users comment; the author comes from the session and `approved` is read-only.
|
|
7
|
+
* - Authors see their own comments while they await moderation, and may edit or delete them.
|
|
8
|
+
* - Moderators (`blog.change_comment`) see everything.
|
|
9
|
+
*/
|
|
10
|
+
import { and, eq, inArray, or } from 'drizzle-orm'
|
|
11
|
+
import { user } from '@knit-framework/core/schema'
|
|
12
|
+
import { ValidationError } from '@knit-framework/core/models'
|
|
13
|
+
import { defineResource, isOwner } from '@knit-framework/core/resources'
|
|
14
|
+
import { comment, post } from '../database/schema'
|
|
15
|
+
|
|
16
|
+
const MODERATE = 'blog.change_comment'
|
|
17
|
+
|
|
18
|
+
export default defineResource(comment, {
|
|
19
|
+
slug: 'comments',
|
|
20
|
+
fields: ['id', 'postId', 'authorId', 'body', 'approved', 'createdAt', 'updatedAt'],
|
|
21
|
+
readonlyFields: ['authorId', 'approved', 'createdAt', 'updatedAt'],
|
|
22
|
+
labels: { body: 'Comment' },
|
|
23
|
+
filterFields: ['postId', 'approved'],
|
|
24
|
+
searchFields: ['body'],
|
|
25
|
+
ordering: ['createdAt'],
|
|
26
|
+
perPage: 50,
|
|
27
|
+
|
|
28
|
+
permissions: {
|
|
29
|
+
list: 'public',
|
|
30
|
+
retrieve: 'public',
|
|
31
|
+
create: 'authenticated',
|
|
32
|
+
update: [isOwner('authorId'), MODERATE],
|
|
33
|
+
delete: [isOwner('authorId'), 'blog.delete_comment'],
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
// Row-level scoping: visitors see approved comments, authors also their own pending ones.
|
|
37
|
+
scope(ctx) {
|
|
38
|
+
if (ctx.can(MODERATE)) return undefined
|
|
39
|
+
return ctx.user ? or(eq(comment.approved, true), eq(comment.authorId, ctx.user.id)) : { approved: true }
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
async beforeCreate(data, ctx) {
|
|
43
|
+
if (!ctx.user) throw new ValidationError('Sign in to comment.')
|
|
44
|
+
const postId = Number(data.postId)
|
|
45
|
+
if (Number.isInteger(postId)) {
|
|
46
|
+
const [target] = await ctx.db.select({ id: post.id }).from(post)
|
|
47
|
+
.where(and(eq(post.id, postId), eq(post.published, true)))
|
|
48
|
+
if (!target) throw new ValidationError({ postId: 'Comments are only open on published posts.' })
|
|
49
|
+
}
|
|
50
|
+
return { ...data, authorId: ctx.user.id }
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
// A comment stays on its post.
|
|
54
|
+
beforeUpdate({ postId: _postId, ...data }) {
|
|
55
|
+
return data
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
// One query for every author on the page (Django: `prefetch_related('author')`).
|
|
59
|
+
async prefetch(rows, ctx) {
|
|
60
|
+
const ids = [...new Set(rows.map(r => r.authorId))]
|
|
61
|
+
if (!ids.length) return new Map<string, string>()
|
|
62
|
+
const authors = await ctx.db.select({ id: user.id, name: user.name }).from(user).where(inArray(user.id, ids))
|
|
63
|
+
return new Map(authors.map(a => [a.id, a.name]))
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
serialize(row, _ctx, authors) {
|
|
67
|
+
return {
|
|
68
|
+
id: row.id,
|
|
69
|
+
postId: row.postId,
|
|
70
|
+
authorId: row.authorId,
|
|
71
|
+
author: { id: row.authorId, name: authors.get(row.authorId) ?? 'Former member' },
|
|
72
|
+
body: row.body,
|
|
73
|
+
approved: row.approved,
|
|
74
|
+
createdAt: row.createdAt,
|
|
75
|
+
updatedAt: row.updatedAt,
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public, read-only posts API (DRF: a `ReadOnlyModelViewSet` with a queryset filter).
|
|
3
|
+
* Visitors see published posts; editors with `blog.change_post` see drafts too and may write.
|
|
4
|
+
* It also makes `postId` options (`/api/r/comments/_choices/postId`) available to forms.
|
|
5
|
+
*/
|
|
6
|
+
import { defineResource } from '@knit-framework/core/resources'
|
|
7
|
+
import { post } from '../database/schema'
|
|
8
|
+
|
|
9
|
+
export default defineResource(post, {
|
|
10
|
+
slug: 'posts',
|
|
11
|
+
fields: ['id', 'title', 'slug', 'body', 'cover', 'published', 'publishedAt', 'categoryId'],
|
|
12
|
+
readonlyFields: ['publishedAt'],
|
|
13
|
+
searchFields: ['title', 'body'],
|
|
14
|
+
filterFields: ['categoryId', 'publishedAt'],
|
|
15
|
+
ordering: ['-publishedAt'],
|
|
16
|
+
perPage: 10,
|
|
17
|
+
permissions: {
|
|
18
|
+
list: 'public',
|
|
19
|
+
retrieve: 'public',
|
|
20
|
+
create: 'blog.add_post',
|
|
21
|
+
update: 'blog.change_post',
|
|
22
|
+
delete: 'blog.delete_post',
|
|
23
|
+
},
|
|
24
|
+
scope: ctx => (ctx.can('blog.change_post') ? undefined : { published: true }),
|
|
25
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { desc, eq } from 'drizzle-orm'
|
|
2
|
+
|
|
3
|
+
/** Blog section of `/sitemap.xml`: the index plus every published post. */
|
|
4
|
+
export default defineSitemap(async () => {
|
|
5
|
+
const posts = await useDB().query.post.findMany({
|
|
6
|
+
where: eq(tables.post.published, true),
|
|
7
|
+
orderBy: desc(tables.post.publishedAt),
|
|
8
|
+
columns: { slug: true, updatedAt: true },
|
|
9
|
+
})
|
|
10
|
+
return [
|
|
11
|
+
{ loc: '/blog', changefreq: 'daily', priority: 0.8 },
|
|
12
|
+
...posts.map(p => ({ loc: `/blog/${p.slug}`, lastmod: p.updatedAt, changefreq: 'weekly' as const })),
|
|
13
|
+
]
|
|
14
|
+
})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example tasks. Task files run both in the Nitro server and in `pnpm manage worker` /
|
|
3
|
+
* `pnpm manage runtask`, so they use `ctx.db` and explicit imports instead of Nitro auto-imports.
|
|
4
|
+
*
|
|
5
|
+
* enqueue('blog.word-count', { postId: 1 }) // from any server route
|
|
6
|
+
* pnpm manage runtask blog.word-count --payload '{"postId":1}'
|
|
7
|
+
*/
|
|
8
|
+
import { count, eq } from 'drizzle-orm'
|
|
9
|
+
import { defineTask } from '@knit-framework/core/tasks'
|
|
10
|
+
import { post } from '../database/schema'
|
|
11
|
+
|
|
12
|
+
export interface WordCountPayload {
|
|
13
|
+
postId: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const wordCount = defineTask({
|
|
17
|
+
name: 'blog.word-count',
|
|
18
|
+
description: 'Counts the words in a blog post.',
|
|
19
|
+
async run(payload: WordCountPayload, ctx) {
|
|
20
|
+
const [row] = await ctx.db
|
|
21
|
+
.select({ title: post.title, body: post.body })
|
|
22
|
+
.from(post)
|
|
23
|
+
.where(eq(post.id, payload.postId))
|
|
24
|
+
if (!row) throw new Error(`Post ${payload.postId} does not exist.`)
|
|
25
|
+
const words = row.body.trim().split(/\s+/).filter(Boolean).length
|
|
26
|
+
ctx.log(`"${row.title}" has ${words} word(s)`)
|
|
27
|
+
return { postId: payload.postId, title: row.title, words }
|
|
28
|
+
},
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
/** Scheduled: the worker (or Nitro's scheduler, while the server runs) enqueues it every 5 minutes. */
|
|
32
|
+
export const blogStats = defineTask({
|
|
33
|
+
name: 'blog.stats',
|
|
34
|
+
description: 'Logs published/draft post counts.',
|
|
35
|
+
schedule: '*/5 * * * *',
|
|
36
|
+
maxAttempts: 1,
|
|
37
|
+
async run(_payload: Record<string, never>, ctx) {
|
|
38
|
+
const rows = await ctx.db
|
|
39
|
+
.select({ published: post.published, total: count() })
|
|
40
|
+
.from(post)
|
|
41
|
+
.groupBy(post.published)
|
|
42
|
+
const stats = {
|
|
43
|
+
published: rows.find(r => r.published)?.total ?? 0,
|
|
44
|
+
drafts: rows.find(r => !r.published)?.total ?? 0,
|
|
45
|
+
}
|
|
46
|
+
ctx.log(`${stats.published} published, ${stats.drafts} draft(s)`)
|
|
47
|
+
return stats
|
|
48
|
+
},
|
|
49
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example app test (Django: `blog/tests.py`). Copy this pattern into your own layers:
|
|
3
|
+
* a fresh in-memory database per file, typed factories, and plain Drizzle queries.
|
|
4
|
+
*/
|
|
5
|
+
import * as coreSchema from '@knit-framework/core/schema'
|
|
6
|
+
import { createTestDatabase, defineFactory, type TestDatabase } from '@knit-framework/core/testing'
|
|
7
|
+
import { eq } from 'drizzle-orm'
|
|
8
|
+
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
|
9
|
+
import * as blogSchema from '../server/database/schema'
|
|
10
|
+
|
|
11
|
+
const schema = { ...coreSchema, ...blogSchema }
|
|
12
|
+
const categories = defineFactory(blogSchema.category, n => ({ name: `Category ${n}`, slug: `category-${n}` }))
|
|
13
|
+
const posts = defineFactory(blogSchema.post, n => ({ title: `Post ${n}`, slug: `post-${n}` }))
|
|
14
|
+
|
|
15
|
+
let t: TestDatabase<typeof schema>
|
|
16
|
+
beforeAll(async () => {
|
|
17
|
+
t = await createTestDatabase({ schema })
|
|
18
|
+
})
|
|
19
|
+
beforeEach(() => t.reset())
|
|
20
|
+
afterAll(() => t.close())
|
|
21
|
+
|
|
22
|
+
describe('blog', () => {
|
|
23
|
+
it('lists only published posts, newest first, with their category', async () => {
|
|
24
|
+
const news = await categories.create(t.db, { name: 'News' })
|
|
25
|
+
await posts.create(t.db, { title: 'Draft', published: false })
|
|
26
|
+
await posts.create(t.db, { title: 'Old', published: true, publishedAt: new Date('2026-01-01'), categoryId: news.id })
|
|
27
|
+
await posts.create(t.db, { title: 'New', published: true, publishedAt: new Date('2026-06-01'), categoryId: news.id })
|
|
28
|
+
|
|
29
|
+
const published = await t.db.query.post.findMany({
|
|
30
|
+
where: eq(blogSchema.post.published, true),
|
|
31
|
+
orderBy: (p, { desc }) => desc(p.publishedAt),
|
|
32
|
+
with: { category: true },
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
expect(published.map(p => p.title)).toEqual(['New', 'Old'])
|
|
36
|
+
expect(published[0]?.category?.name).toBe('News')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('nulls a post’s category when the category is deleted', async () => {
|
|
40
|
+
const tmp = await categories.create(t.db)
|
|
41
|
+
const post = await posts.create(t.db, { categoryId: tmp.id })
|
|
42
|
+
await t.db.delete(blogSchema.category).where(eq(blogSchema.category.id, tmp.id))
|
|
43
|
+
const [reloaded] = await t.db.select().from(blogSchema.post).where(eq(blogSchema.post.id, post.id))
|
|
44
|
+
expect(reloaded?.categoryId).toBeNull()
|
|
45
|
+
})
|
|
46
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** The blog's locale files stay in sync: same page strings everywhere, same model text in de/es. */
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
type Messages = { [key: string]: string | Messages }
|
|
6
|
+
const load = (code: string): Messages =>
|
|
7
|
+
JSON.parse(readFileSync(new URL(`../i18n/locales/${code}.json`, import.meta.url), 'utf8')) as Messages
|
|
8
|
+
|
|
9
|
+
function keys(messages: Messages, prefix = ''): string[] {
|
|
10
|
+
return Object.entries(messages).flatMap(([k, v]) => (typeof v === 'string' ? [prefix + k] : keys(v, `${prefix}${k}.`))).sort()
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const en = load('en')
|
|
14
|
+
const de = load('de')
|
|
15
|
+
const es = load('es')
|
|
16
|
+
|
|
17
|
+
describe('example-blog locales', () => {
|
|
18
|
+
it('every language has every page string', () => {
|
|
19
|
+
const pageKeys = keys(en.blog as Messages)
|
|
20
|
+
expect(keys(de.blog as Messages)).toEqual(pageKeys)
|
|
21
|
+
expect(keys(es.blog as Messages)).toEqual(pageKeys)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('German and Spanish translate the same model text', () => {
|
|
25
|
+
expect(keys(de.knit as Messages)).toEqual(keys(es.knit as Messages))
|
|
26
|
+
})
|
|
27
|
+
})
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
// Type-only: the dashboard reads the blog's public `posts` resource.
|
|
3
|
+
import type { post } from '../../../example-blog/server/database/schema'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Rendered in the browser only: this layer sets `knit: { spa: true }`, so the server sends an
|
|
7
|
+
* empty shell and Vue renders here. Browser-only APIs are safe to use directly.
|
|
8
|
+
*/
|
|
9
|
+
const { t, locale } = useI18n()
|
|
10
|
+
useHead({ title: () => t('dashboard.title') })
|
|
11
|
+
|
|
12
|
+
const posts = useResource<typeof post>('posts').list({ perPage: 100, key: 'dashboard-posts' })
|
|
13
|
+
|
|
14
|
+
const browser = reactive({
|
|
15
|
+
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
16
|
+
online: navigator.onLine,
|
|
17
|
+
viewport: `${window.innerWidth} × ${window.innerHeight}`,
|
|
18
|
+
})
|
|
19
|
+
const update = () => {
|
|
20
|
+
browser.online = navigator.onLine
|
|
21
|
+
browser.viewport = `${window.innerWidth} × ${window.innerHeight}`
|
|
22
|
+
}
|
|
23
|
+
onMounted(() => {
|
|
24
|
+
window.addEventListener('online', update)
|
|
25
|
+
window.addEventListener('offline', update)
|
|
26
|
+
window.addEventListener('resize', update)
|
|
27
|
+
})
|
|
28
|
+
onBeforeUnmount(() => {
|
|
29
|
+
window.removeEventListener('online', update)
|
|
30
|
+
window.removeEventListener('offline', update)
|
|
31
|
+
window.removeEventListener('resize', update)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const latest = computed(() => posts.items.value[0])
|
|
35
|
+
</script>
|
|
36
|
+
|
|
37
|
+
<template>
|
|
38
|
+
<UContainer class="space-y-8 py-12">
|
|
39
|
+
<div class="space-y-2">
|
|
40
|
+
<UBadge color="primary" variant="subtle" icon="i-lucide-monitor-smartphone" :label="t('dashboard.badge')" />
|
|
41
|
+
<h1 class="text-3xl font-bold text-highlighted">
|
|
42
|
+
{{ t('dashboard.title') }}
|
|
43
|
+
</h1>
|
|
44
|
+
<p class="text-muted">
|
|
45
|
+
{{ t('dashboard.intro') }}
|
|
46
|
+
</p>
|
|
47
|
+
</div>
|
|
48
|
+
|
|
49
|
+
<div class="grid gap-4 sm:grid-cols-3">
|
|
50
|
+
<UCard>
|
|
51
|
+
<p class="text-sm text-muted">{{ t('dashboard.published') }}</p>
|
|
52
|
+
<p class="text-3xl font-semibold text-highlighted" data-testid="post-count">{{ posts.total.value }}</p>
|
|
53
|
+
</UCard>
|
|
54
|
+
<UCard>
|
|
55
|
+
<p class="text-sm text-muted">{{ t('dashboard.latest') }}</p>
|
|
56
|
+
<p class="truncate font-medium text-highlighted">{{ latest?.title ?? '—' }}</p>
|
|
57
|
+
</UCard>
|
|
58
|
+
<UCard>
|
|
59
|
+
<p class="text-sm text-muted">{{ t('dashboard.browser') }}</p>
|
|
60
|
+
<p class="font-medium text-highlighted">{{ browser.timeZone }}</p>
|
|
61
|
+
<p class="text-sm text-muted">
|
|
62
|
+
{{ browser.viewport }} · {{ browser.online ? t('dashboard.online') : t('dashboard.offline') }} · {{ locale }}
|
|
63
|
+
</p>
|
|
64
|
+
</UCard>
|
|
65
|
+
</div>
|
|
66
|
+
</UContainer>
|
|
67
|
+
</template>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"dashboard": {
|
|
3
|
+
"title": "Dashboard",
|
|
4
|
+
"badge": "Im Browser gerendert",
|
|
5
|
+
"intro": "Diese Seite ist eine SPA: Ihre Ebene setzt knit.spa, deshalb rendert sie in Ihrem Browser.",
|
|
6
|
+
"published": "Veröffentlichte Beiträge",
|
|
7
|
+
"latest": "Neuester Beitrag",
|
|
8
|
+
"browser": "Ihr Browser",
|
|
9
|
+
"online": "online",
|
|
10
|
+
"offline": "offline"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"dashboard": {
|
|
3
|
+
"title": "Dashboard",
|
|
4
|
+
"badge": "Client-side rendered",
|
|
5
|
+
"intro": "This page is a SPA: its layer sets knit.spa, so it renders in your browser.",
|
|
6
|
+
"published": "Published posts",
|
|
7
|
+
"latest": "Latest post",
|
|
8
|
+
"browser": "Your browser",
|
|
9
|
+
"online": "online",
|
|
10
|
+
"offline": "offline"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"dashboard": {
|
|
3
|
+
"title": "Panel",
|
|
4
|
+
"badge": "Renderizado en el cliente",
|
|
5
|
+
"intro": "Esta página es una SPA: su capa activa knit.spa, así que se renderiza en tu navegador.",
|
|
6
|
+
"published": "Publicaciones publicadas",
|
|
7
|
+
"latest": "Última publicación",
|
|
8
|
+
"browser": "Tu navegador",
|
|
9
|
+
"online": "en línea",
|
|
10
|
+
"offline": "sin conexión"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Example of a layer rendered as a client-side SPA (no server-side rendering for its pages),
|
|
3
|
+
* e.g. a dashboard that only makes sense with browser APIs. See docs/rendering.md.
|
|
4
|
+
*/
|
|
5
|
+
export default defineNuxtConfig({
|
|
6
|
+
$meta: {
|
|
7
|
+
name: 'example-dashboard',
|
|
8
|
+
},
|
|
9
|
+
knit: {
|
|
10
|
+
spa: true,
|
|
11
|
+
},
|
|
12
|
+
})
|