create-knit 0.7.1 → 0.9.0
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/package.json +1 -1
- package/template/base/.claude/skills/knit-add-api/SKILL.md +27 -2
- package/template/base/.claude/skills/knit-add-model/SKILL.md +1 -0
- package/template/base/.claude/skills/knit-add-permission/SKILL.md +2 -1
- package/template/base/AGENTS.md +3 -2
- package/template/base/apps/web/.env.example +11 -0
- package/template/base/llms.txt +3 -0
- package/template/examples/layers/example-blog/admin.ts +45 -2
- package/template/examples/layers/example-blog/app/admin/BlogStatsCard.vue +26 -0
- package/template/examples/layers/example-blog/app/admin/BodyInput.vue +29 -0
- package/template/examples/layers/example-blog/app/admin/CommentsCell.vue +18 -0
- package/template/examples/layers/example-blog/app/admin/PostComments.vue +42 -0
- package/template/examples/layers/example-blog/app/pages/admin/blog-insights.vue +56 -0
- package/template/examples/layers/example-blog/i18n/locales/de.json +30 -2
- package/template/examples/layers/example-blog/i18n/locales/en.json +16 -1
- package/template/examples/layers/example-blog/i18n/locales/es.json +30 -2
- package/template/examples/layers/example-blog/server/api/blog/insights.get.ts +25 -0
- package/template/examples/layers/example-blog/server/api/blog/posts/[slug].get.ts +1 -1
- package/template/examples/layers/example-blog/server/api/blog/posts.get.ts +2 -2
- package/template/examples/layers/example-blog/server/api/blog/word-count.post.ts +31 -20
- package/template/examples/layers/example-blog/server/database/schema.ts +18 -4
- package/template/examples/layers/example-blog/server/feeds/blog.ts +2 -2
- package/template/examples/layers/example-blog/server/sitemaps/blog.ts +2 -2
- package/template/examples/layers/example-blog/server/tasks/blog.ts +2 -0
- package/template/versions.json +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: knit-add-api
|
|
3
|
-
description: Expose a Knit model as a public REST API with permissions (defineResource) and build forms or pages on
|
|
3
|
+
description: Expose a Knit model as a public REST API with permissions (defineResource), add custom JSON endpoints with validated input (defineEndpoint), and build forms or pages on them (useResource, KnitModelForm). Use when asked for an API endpoint, a public form, a CRUD page, an action route ("publish", "import", "checkout"), or "let users create/edit X" in a Knit project.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Add a public API (resource) and forms
|
|
@@ -39,4 +39,29 @@ description: Expose a Knit model as a public REST API with permissions (defineRe
|
|
|
39
39
|
- `knit_check` / `pnpm -s manage check --json`, `pnpm typecheck` and `pnpm lint`.
|
|
40
40
|
- An e2e test with `createTestClient` from `@knit-framework/core/testing` covering one allowed and one denied write.
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
## Not CRUD? A custom endpoint
|
|
43
|
+
|
|
44
|
+
For an action on one or more tables ("publish this post", "count the words", "import a CSV"), write a route file with `defineEndpoint` instead of a bare `defineEventHandler`:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
// layers/shop/server/api/shop/products/[id]/restock.post.ts
|
|
48
|
+
import { defineEndpoint, z } from '@knit-framework/core/endpoints'
|
|
49
|
+
|
|
50
|
+
export default defineEndpoint({
|
|
51
|
+
summary: 'Restock a product',
|
|
52
|
+
permission: 'shop.change_product', // required
|
|
53
|
+
params: z.object({ id: z.coerce.number().int().positive() }), // path and query values are strings: z.coerce
|
|
54
|
+
body: z.object({ quantity: z.number().int().positive() }), // invalid → 422 with data.issues
|
|
55
|
+
response: z.object({ id: z.number(), stock: z.number() }), // keys it doesn't list are dropped
|
|
56
|
+
handler: async ({ params, body, actor }) => {
|
|
57
|
+
const products = useModel(tables.product).as(actor) // applies row-level policies
|
|
58
|
+
const product = await products.get(params.id)
|
|
59
|
+
const saved = await products.update(params.id, { stock: product.stock + body.quantity })
|
|
60
|
+
return { id: saved.id, stock: saved.stock }
|
|
61
|
+
},
|
|
62
|
+
})
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
It shows up in `/api/r/openapi.json` and in `pnpm -s manage routes --json --kind api` with its permission. Test one allowed and one denied call with `createTestClient`, or call `runEndpoint()` without a server.
|
|
66
|
+
|
|
67
|
+
Guides: `knit_docs` topics `resources` and `endpoints` (or `node_modules/@knit-framework/core/docs/resources.md`, `node_modules/@knit-framework/core/docs/endpoints.md`).
|
|
@@ -22,6 +22,7 @@ description: Add or change a model (Drizzle table) in a Knit app, end to end - s
|
|
|
22
22
|
- If it says drizzle-kit must ask about a rename, split the change: add the new column, migrate, then drop the old one.
|
|
23
23
|
5. **Apply it** with `pnpm manage migrate`. This works while `pnpm dev` runs, and `pnpm dev` also applies migrations when it starts.
|
|
24
24
|
6. **Admin:** register the table in `layers/<app>/admin.ts` with `registerAdminModel(table, { listDisplay, searchFields, listFilter, ordering, readonlyFields })`, using field *keys* (camelCase JS names). A running `pnpm dev` picks up a new or changed `admin.ts` without a restart.
|
|
25
|
+
- Need more than options? A count or other derived value in the list is a computed column (`listDisplay: ['title', { name: 'comments', value: (row, { objects }) => objects(comment).count({ postId: row.id }) }]`); a special input is a custom widget (`widgets: { color: { component: 'ColorPicker' } }`); extra content on the change form is a panel (`panels: [{ component: 'PostComments' }]`). Components go in `layers/<app>/app/admin/<Name>.vue` and are named without the `Admin` prefix. Dashboard cards and custom admin pages: `registerDashboardCard`, `registerAdminPage`. See "Extending the admin" in `node_modules/@knit-framework/core/docs/admin.md`.
|
|
25
26
|
7. **Verify.**
|
|
26
27
|
- `pnpm -s manage check --json` (MCP: `knit_check`) has no errors. It catches unknown admin fields, missing prefixes and clashes.
|
|
27
28
|
- `pnpm typecheck` and `pnpm lint` pass.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: knit-add-permission
|
|
3
|
-
description: Add a custom permission to a Knit app, enforce it on the server and grant it to a group or user - customPermissions, requirePermission, resource rules, row-level policies, seeds and a denied-request test. Use when asked to restrict who can do something, add a role-like capability ("only editors can publish"), limit users to their own rows ("editors change only their own posts"), or grant permissions in a Knit project.
|
|
3
|
+
description: Add a custom permission to a Knit app, enforce it on the server and grant it to a group or user - customPermissions, requirePermission, resource rules, row-level policies (incl. organization-scoped rows), seeds and a denied-request test. Use when asked to restrict who can do something, add a role-like capability ("only editors can publish"), limit users to their own rows ("editors change only their own posts") or their organization's rows ("each team sees only its projects"), or grant permissions in a Knit project.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Add a permission and grant it
|
|
@@ -14,6 +14,7 @@ description: Add a custom permission to a Knit app, enforce it on the server and
|
|
|
14
14
|
- Server route: `await requirePermission(event, 'blog.publish_post')` in a route under `layers/<app>/server/api/` (auto-imported there).
|
|
15
15
|
- Resource: put the name in the action's rule, e.g. `permissions: { update: 'blog.publish_post' }` or `[isOwner('authorId'), 'blog.change_post']` (any rule allows).
|
|
16
16
|
- Only some rows ("their own posts", "their team's tickets"): a row-level policy on the model, in `layers/<app>/server/database/schema.ts` (`pnpm manage generate policy <app> <model>` writes a starting one): `defineModelMeta(table, { policy: { assignOwner: 'authorId', change: [isRowOwner('authorId'), 'blog.change_any_post'] } })`. The admin, resources and broadcasts all apply it; your own server code applies it with `useModel(table).as(await requestActor(event))`. Use `scope` only for rows a user must not see at all (it hides them from visitors too). Guide: `knit_docs { "topic": "permissions" }`.
|
|
17
|
+
- Rows that belong to an organization ("each customer sees only their company's projects"): turn on organizations (`NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED=true`), give the model an `organizationId` column referencing `organization.id` from `@knit-framework/core/schema`, and run `pnpm manage generate policy <app> <model> --organization`: `scope: inActiveOrganization('organizationId')`, `assignOrganization: 'organizationId'`, and `hasOrganizationRole('owner', 'admin')` for what only the organization's admins may do. `ctx.organization` (`{ id, role }` or `null`) is in every rule. In tests, `createTestClient().switchOrganization(id)`. Guide: `knit_docs { "topic": "organizations" }`.
|
|
17
18
|
4. **Create the permission rows.** The server creates them when it starts. A running `pnpm dev` reloads on the `admin.ts` change; restart it if the permission is still unknown. Granting before that fails with `KNIT_E1903` (`knit_docs { "topic": "errors/KNIT_E1903" }`).
|
|
18
19
|
5. **Grant it.**
|
|
19
20
|
- By hand: `/admin/auth/groups/:id` (a matrix per group) or `/admin/auth/users/:id`.
|
package/template/base/AGENTS.md
CHANGED
|
@@ -29,10 +29,10 @@ Don't read files to find out what exists. Ask Knit:
|
|
|
29
29
|
| A new app | `pnpm manage startapp <name>` → `layers/<name>/` with a model, admin, API, page, seed, command and test (adds it to `apps/web/nuxt.config.ts` `extends`) |
|
|
30
30
|
| One more file in an app | `pnpm manage generate <resource\|task\|channel\|command\|test\|page> <app> <name> [--table <export>]`: start from the generated file instead of writing it from scratch |
|
|
31
31
|
| Models | `layers/<app>/server/database/schema.ts` (tables named `<app>_<model>`, `relations()` next to them) |
|
|
32
|
-
| Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })` |
|
|
32
|
+
| Admin | `layers/<app>/admin.ts` → `registerAdminModel(table, { listDisplay, searchFields, … })`; `registerAdminPage`, `registerDashboardCard`; your admin components in `layers/<app>/app/admin/*.vue` (widgets, computed columns, panels, cards) |
|
|
33
33
|
| A public REST API + forms | `layers/<app>/server/resources/<name>.ts` → `export default defineResource(table, { permissions, … })`; `<KnitModelForm resource="…">` in pages |
|
|
34
34
|
| Pages / components | `layers/<app>/app/pages/**`, `app/components/**` (Nuxt conventions) |
|
|
35
|
-
| Server endpoints | `layers/<app>/server/api/**` (`useDB()`, `tables`, `useModel()` are auto-imported
|
|
35
|
+
| Server endpoints | `layers/<app>/server/api/**` → `export default defineEndpoint({ permission, body, response, handler })` from `@knit-framework/core/endpoints` (validated, permission-checked, in the OpenAPI document). `useDB()`, `tables`, `useModel()` are auto-imported |
|
|
36
36
|
| Background / scheduled work | `layers/<app>/server/tasks/*.ts` → `defineTask` from `@knit-framework/core/tasks` |
|
|
37
37
|
| Realtime | `layers/<app>/server/channels/*.ts` → `defineChannel`; `broadcastModel` in the schema |
|
|
38
38
|
| CLI commands / seeds | `layers/<app>/commands/<name>.ts` (`defineManageCommand`), `server/database/seed.ts` (`defineSeed`) |
|
|
@@ -48,6 +48,7 @@ Don't edit `node_modules/@knit-framework/*`: override instead (a page, component
|
|
|
48
48
|
- **Cross-app references** import the table: `import { user } from '@knit-framework/core/schema'`.
|
|
49
49
|
- **Permissions on the server:** `requirePermission(event, 'shop.change_product')`. In the UI, `useAuth().can(perm)` is display-only.
|
|
50
50
|
- **Row-level rules** ("users change only their own rows") are a `policy` in the model's meta, not checks in each route. In your own routes, act as the user so it applies: `useModel(table).as(await requestActor(event))`; plain `useModel(table)` and `useDB()` skip it. See `node_modules/@knit-framework/core/docs/permissions.md`.
|
|
51
|
+
- **Custom JSON routes use `defineEndpoint`**, not a bare `defineEventHandler`: it requires a `permission`, validates `body`/`query`/`params` with zod (`z` comes from `@knit-framework/core/endpoints`; query and params arrive as strings, so `z.coerce`), answers with the same 422 `data.issues` as model validation, and lists the route in `/api/r/openapi.json`. Plain handlers are for non-JSON routes (downloads, redirects, raw-body webhooks). See `node_modules/@knit-framework/core/docs/endpoints.md`.
|
|
51
52
|
- **Resources default to deny for writes.** List `fields` explicitly for public APIs. Server-set values (e.g. `authorId`) belong in `beforeCreate`.
|
|
52
53
|
- **Files outside Nitro** (tasks, commands, seeds) don't get auto-imports: import from `@knit-framework/core/*` and use the `db`/`ctx.db` you are given.
|
|
53
54
|
- **UI strings** go through `t()`; a literal `{`, `}`, `@` or `|` in a locale message breaks the whole language.
|
|
@@ -30,6 +30,9 @@ NUXT_BETTER_AUTH_URL=
|
|
|
30
30
|
# First-admin setup wizard at /admin/setup: dev (default) | always | never
|
|
31
31
|
# NUXT_KNIT_ALLOW_SETUP=dev
|
|
32
32
|
|
|
33
|
+
# Days to keep model change history (knit_history); a daily task deletes older entries. 0 (default) keeps it forever
|
|
34
|
+
# NUXT_KNIT_HISTORY_KEEP_DAYS=365
|
|
35
|
+
|
|
33
36
|
# Site name used in auth emails. Default: Knit
|
|
34
37
|
# NUXT_BETTER_AUTH_APP_NAME=Knit
|
|
35
38
|
|
|
@@ -64,6 +67,14 @@ NUXT_BETTER_AUTH_URL=
|
|
|
64
67
|
# NUXT_KNIT_AUTH_TWO_FACTOR=optional
|
|
65
68
|
# Passkeys (WebAuthn): true (default) | false
|
|
66
69
|
# NUXT_KNIT_AUTH_PASSKEYS=true
|
|
70
|
+
# Organizations (docs/organizations.md): users create them, invite members and switch the active one
|
|
71
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED=false
|
|
72
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_ALLOW_USER_TO_CREATE=true
|
|
73
|
+
# Creator's role: owner (default) | admin
|
|
74
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_CREATOR_ROLE=owner
|
|
75
|
+
# Invitation lifetime in seconds (default 48 hours)
|
|
76
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_INVITATION_EXPIRES_IN=172800
|
|
77
|
+
# NUXT_KNIT_AUTH_ORGANIZATIONS_MEMBERSHIP_LIMIT=100
|
|
67
78
|
|
|
68
79
|
# Email. Mailer: console (dev default, prints to the terminal) | smtp | memory (in-process outbox)
|
|
69
80
|
# Empty mailer = smtp when NUXT_MAIL_URL is set, otherwise console.
|
package/template/base/llms.txt
CHANGED
|
@@ -16,10 +16,12 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
16
16
|
- [Getting started](node_modules/@knit-framework/core/docs/getting-started.md): Install, project layout, your first app end to end
|
|
17
17
|
- [Models & data](node_modules/@knit-framework/core/docs/models.md): Tables, migrations, `useModel`, validators, `clean()`, signals, Postgres
|
|
18
18
|
- [Resources & forms](node_modules/@knit-framework/core/docs/resources.md): `defineResource` REST APIs, permissions, scoping, OpenAPI, `useResource`, `<KnitModelForm>`
|
|
19
|
+
- [Custom endpoints](node_modules/@knit-framework/core/docs/endpoints.md): `defineEndpoint` routes with a permission, validated input and an entry in the OpenAPI document
|
|
19
20
|
- [Rendering modes](node_modules/@knit-framework/core/docs/rendering.md): SSR by default; SPA per route, per path or per layer; prerender and caching
|
|
20
21
|
- [Admin](node_modules/@knit-framework/core/docs/admin.md): `registerAdminModel` options, filters, actions, inlines, history, user tools, REST API
|
|
21
22
|
- [Auth & permissions](node_modules/@knit-framework/core/docs/auth.md): Users, staff, superusers, groups, permissions, `/accounts/*` pages
|
|
22
23
|
- [Row-level permissions](node_modules/@knit-framework/core/docs/permissions.md): `defineModelMeta(table, { policy })`, `useModel(table).as(actor)`, what the admin, resources and realtime apply
|
|
24
|
+
- [Organizations](node_modules/@knit-framework/core/docs/organizations.md): `NUXT_KNIT_AUTH_ORGANIZATIONS_ENABLED`, invitations, roles, `inActiveOrganization` / `hasOrganizationRole` / `assignOrganization`, `useOrganization()`, `switchOrganization()` in tests
|
|
23
25
|
- [Internationalization](node_modules/@knit-framework/core/docs/i18n.md): Translations, locales per layer, translating models, the language switcher
|
|
24
26
|
- [Email](node_modules/@knit-framework/core/docs/email.md): `sendMail()`, mailers, templates, auth emails
|
|
25
27
|
- [Background tasks](node_modules/@knit-framework/core/docs/tasks.md): `defineTask`, `enqueue`, the worker, cron schedules
|
|
@@ -31,6 +33,7 @@ Agents working in a Knit project: read AGENTS.md, and use the `knit` MCP server
|
|
|
31
33
|
- [Logging](node_modules/@knit-framework/core/docs/logging.md): LogLayer: pretty dev output, JSON in production, request logs, redaction
|
|
32
34
|
- [Security](node_modules/@knit-framework/core/docs/security.md): CSRF, security headers, CSP
|
|
33
35
|
- [Testing](node_modules/@knit-framework/core/docs/testing.md): Test databases, factories, the HTTP client, `pnpm test`
|
|
36
|
+
- [Knit in Nuxt DevTools](node_modules/@knit-framework/core/docs/devtools.md): the dev-only Knit tab (models, routes, tasks, mail, realtime, errors, migrations), its actions and who may read it
|
|
34
37
|
- [`manage` CLI](node_modules/@knit-framework/core/docs/cli.md): Every command, `startapp` and `generate`, JSON output for scripts and agents, seeds, custom commands
|
|
35
38
|
- [Configuration](node_modules/@knit-framework/core/docs/configuration.md): Every environment variable and setting
|
|
36
39
|
- [Deployment](node_modules/@knit-framework/core/docs/deployment/index.md): production checklist, what Knit needs from a host, and one page per host (Docker, VPS with systemd and Caddy, Fly.io, Railway, Render; Vercel and Netlify with limits; Cloudflare not supported)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { inArray, sql } from 'drizzle-orm'
|
|
2
|
-
import { manyToMany, registerAdminModel, tabularInline } from '@knit-framework/core/admin'
|
|
2
|
+
import { manyToMany, registerAdminModel, registerAdminPage, registerDashboardCard, tabularInline } from '@knit-framework/core/admin'
|
|
3
3
|
import { useModel, type ModelDatabase } from '@knit-framework/core/models'
|
|
4
4
|
import { category, comment, post, postTag, tag } from './server/database/schema'
|
|
5
5
|
|
|
@@ -28,7 +28,28 @@ registerAdminModel(post, {
|
|
|
28
28
|
icon: 'i-lucide-file-text',
|
|
29
29
|
// Editors change their own posts (the policy in schema.ts); this lets an editor-in-chief change any.
|
|
30
30
|
customPermissions: ['change_any_post'],
|
|
31
|
-
listDisplay: [
|
|
31
|
+
listDisplay: [
|
|
32
|
+
'title',
|
|
33
|
+
'published',
|
|
34
|
+
'categoryId',
|
|
35
|
+
// A computed column: counted on the server for each row, rendered by app/admin/CommentsCell.vue.
|
|
36
|
+
{
|
|
37
|
+
name: 'comments',
|
|
38
|
+
label: 'Comments',
|
|
39
|
+
component: 'CommentsCell',
|
|
40
|
+
async value(row, { objects }) {
|
|
41
|
+
// `objects` acts as the signed-in admin, so the comments' row-level scope applies.
|
|
42
|
+
const comments = objects(comment)
|
|
43
|
+
return { approved: await comments.count({ postId: row.id, approved: true }), pending: await comments.count({ postId: row.id, approved: false }) }
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
'publishedAt',
|
|
47
|
+
'updatedAt',
|
|
48
|
+
],
|
|
49
|
+
// A custom widget: app/admin/BodyInput.vue (a textarea with a word count); list cells keep the default text.
|
|
50
|
+
widgets: { body: { component: 'BodyInput', cell: false } },
|
|
51
|
+
// An edit-page panel: the post's latest comments (app/admin/PostComments.vue).
|
|
52
|
+
panels: [{ component: 'PostComments', position: 'sidebar', title: 'Recent comments' }],
|
|
32
53
|
listEditable: ['published'],
|
|
33
54
|
listFilter: ['published', 'categoryId', 'authorId', 'publishedAt'],
|
|
34
55
|
dateHierarchy: 'publishedAt',
|
|
@@ -126,3 +147,25 @@ registerAdminModel(comment, {
|
|
|
126
147
|
},
|
|
127
148
|
],
|
|
128
149
|
})
|
|
150
|
+
|
|
151
|
+
// A dashboard card (app/admin/BlogStatsCard.vue), shown to users who may view posts.
|
|
152
|
+
registerDashboardCard({
|
|
153
|
+
name: 'blog-stats',
|
|
154
|
+
component: 'BlogStatsCard',
|
|
155
|
+
title: 'Blog',
|
|
156
|
+
size: 'md',
|
|
157
|
+
permission: 'blog.view_post',
|
|
158
|
+
async data({ objects }) {
|
|
159
|
+
const posts = objects(post)
|
|
160
|
+
const comments = objects(comment)
|
|
161
|
+
return {
|
|
162
|
+
posts: await posts.count(),
|
|
163
|
+
published: await posts.count({ published: true }),
|
|
164
|
+
comments: await comments.count(),
|
|
165
|
+
pending: await comments.count({ approved: false }),
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
// A custom admin page: app/pages/admin/blog-insights.vue, linked in the Blog group.
|
|
171
|
+
registerAdminPage({ path: 'blog-insights', label: 'Insights', icon: 'i-lucide-chart-line', group: 'Blog', permission: 'blog.view_post' })
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* Dashboard card (registerDashboardCard in admin.ts): post and comment counts. `data` is what the
|
|
4
|
+
* card's `data()` returned on the server; `refresh` loads it again.
|
|
5
|
+
*/
|
|
6
|
+
const props = defineProps<{
|
|
7
|
+
data: { posts: number, published: number, comments: number, pending: number } | null
|
|
8
|
+
refresh: () => Promise<void>
|
|
9
|
+
}>()
|
|
10
|
+
|
|
11
|
+
const { t, n } = useI18n()
|
|
12
|
+
const stats = computed(() => [
|
|
13
|
+
{ label: t('blog.admin.posts'), value: props.data?.posts ?? 0, hint: t('blog.admin.published', { count: n(props.data?.published ?? 0) }), to: '/admin/blog_post' },
|
|
14
|
+
{ label: t('blog.admin.comments'), value: props.data?.comments ?? 0, hint: t('blog.admin.pending', { count: n(props.data?.pending ?? 0) }), to: '/admin/blog_comment?f.approved=false' },
|
|
15
|
+
])
|
|
16
|
+
</script>
|
|
17
|
+
|
|
18
|
+
<template>
|
|
19
|
+
<div class="grid grid-cols-2 gap-4">
|
|
20
|
+
<NuxtLink v-for="stat in stats" :key="stat.label" :to="stat.to" class="group rounded-lg p-1 -m-1 hover:bg-elevated/50">
|
|
21
|
+
<p class="text-xs text-muted">{{ stat.label }}</p>
|
|
22
|
+
<p class="text-2xl font-semibold text-highlighted tabular-nums">{{ n(stat.value) }}</p>
|
|
23
|
+
<p class="text-xs text-muted group-hover:text-primary">{{ stat.hint }}</p>
|
|
24
|
+
</NuxtLink>
|
|
25
|
+
</div>
|
|
26
|
+
</template>
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* Custom admin widget for a post's body (`widgets: { body: { component: 'BodyInput' } }`):
|
|
4
|
+
* a textarea with a live word count and reading time. Gets `v-model`, `field` and `disabled`.
|
|
5
|
+
*/
|
|
6
|
+
import type { AdminFieldMeta } from '@knit-framework/core/admin/types'
|
|
7
|
+
|
|
8
|
+
defineProps<{
|
|
9
|
+
field: AdminFieldMeta
|
|
10
|
+
disabled?: boolean
|
|
11
|
+
}>()
|
|
12
|
+
const model = defineModel<unknown>()
|
|
13
|
+
|
|
14
|
+
const { t, n } = useI18n()
|
|
15
|
+
const text = computed<string>({
|
|
16
|
+
get: () => (typeof model.value === 'string' ? model.value : ''),
|
|
17
|
+
set: (value) => { model.value = value },
|
|
18
|
+
})
|
|
19
|
+
const words = computed(() => text.value.split(/\s+/).filter(Boolean).length)
|
|
20
|
+
</script>
|
|
21
|
+
|
|
22
|
+
<template>
|
|
23
|
+
<div class="space-y-1">
|
|
24
|
+
<UTextarea v-model="text" :disabled="disabled" :rows="10" autoresize class="w-full" />
|
|
25
|
+
<p class="text-xs text-muted tabular-nums">
|
|
26
|
+
{{ t('blog.admin.wordCount', { words: n(words), minutes: n(Math.max(1, Math.round(words / 230))) }) }}
|
|
27
|
+
</p>
|
|
28
|
+
</div>
|
|
29
|
+
</template>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/** List cell of the posts' computed "comments" column: approved and pending counts, linking to the comments. */
|
|
3
|
+
const props = defineProps<{
|
|
4
|
+
value: { approved: number, pending: number } | null
|
|
5
|
+
row: Record<string, unknown>
|
|
6
|
+
}>()
|
|
7
|
+
|
|
8
|
+
const { t, n } = useI18n()
|
|
9
|
+
const to = computed(() => `/admin/blog_comment?f.postId=${encodeURIComponent(String(props.row['id']))}`)
|
|
10
|
+
</script>
|
|
11
|
+
|
|
12
|
+
<template>
|
|
13
|
+
<span v-if="!value" class="text-dimmed">—</span>
|
|
14
|
+
<NuxtLink v-else :to="to" class="inline-flex items-center gap-1.5" :aria-label="t('blog.admin.commentCounts', { approved: n(value.approved), pending: n(value.pending) })">
|
|
15
|
+
<UBadge color="neutral" variant="subtle" icon="i-lucide-message-square" :label="n(value.approved)" />
|
|
16
|
+
<UBadge v-if="value.pending" color="warning" variant="subtle" icon="i-lucide-clock" :label="n(value.pending)" />
|
|
17
|
+
</NuxtLink>
|
|
18
|
+
</template>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* Edit-page panel of a post (`panels: [{ component: 'PostComments' }]`): its five latest comments,
|
|
4
|
+
* from the comments' admin list (so the user's comment permissions and scope apply).
|
|
5
|
+
* Gets `row` (the post), `meta` (the post model's metadata) and `refresh`.
|
|
6
|
+
*/
|
|
7
|
+
import type { AdminListResponse, AdminModelMeta, AdminRow } from '@knit-framework/core/admin/types'
|
|
8
|
+
|
|
9
|
+
const props = defineProps<{
|
|
10
|
+
row: AdminRow
|
|
11
|
+
meta: AdminModelMeta
|
|
12
|
+
refresh: () => Promise<void>
|
|
13
|
+
}>()
|
|
14
|
+
|
|
15
|
+
const { t, locale } = useI18n()
|
|
16
|
+
const postId = computed(() => String(props.row['id']))
|
|
17
|
+
const { data, error } = useFetch<AdminListResponse>('/api/_admin/blog_comment', {
|
|
18
|
+
query: { 'f.postId': postId, 'perPage': 5, 'sort': '-createdAt' },
|
|
19
|
+
key: `blog-post-comments-${postId.value}`,
|
|
20
|
+
lazy: true,
|
|
21
|
+
})
|
|
22
|
+
</script>
|
|
23
|
+
|
|
24
|
+
<template>
|
|
25
|
+
<!-- Users who may not view comments get a 403 here: the panel then stays empty. -->
|
|
26
|
+
<p v-if="error" class="text-sm text-muted">{{ t('blog.admin.commentsUnavailable') }}</p>
|
|
27
|
+
<div v-else class="space-y-3 text-sm">
|
|
28
|
+
<ul v-if="data?.items.length" class="space-y-2">
|
|
29
|
+
<li v-for="item in data.items" :key="String(item['id'])" class="flex items-start gap-2">
|
|
30
|
+
<UIcon :name="item['approved'] ? 'i-lucide-check' : 'i-lucide-clock'" :class="item['approved'] ? 'text-success' : 'text-warning'" class="mt-0.5 size-3.5 shrink-0" />
|
|
31
|
+
<div class="min-w-0">
|
|
32
|
+
<NuxtLink :to="`/admin/blog_comment/${String(item['id'])}`" class="line-clamp-2 text-highlighted hover:text-primary">{{ item['body'] }}</NuxtLink>
|
|
33
|
+
<NuxtTime :datetime="String(item['createdAt'])" :locale="locale" relative class="text-xs text-muted" />
|
|
34
|
+
</div>
|
|
35
|
+
</li>
|
|
36
|
+
</ul>
|
|
37
|
+
<p v-else class="text-muted">{{ t('blog.noComments') }}</p>
|
|
38
|
+
<ULink v-if="data?.total" :to="`/admin/blog_comment?f.postId=${postId}`" class="text-xs text-muted hover:text-highlighted">
|
|
39
|
+
{{ t('blog.admin.allComments', { count: data.total }) }}
|
|
40
|
+
</ULink>
|
|
41
|
+
</div>
|
|
42
|
+
</template>
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* A custom admin page, linked in the sidebar by `registerAdminPage({ path: 'blog-insights' })` in
|
|
4
|
+
* admin.ts. The admin layout signs users in; the data endpoint checks `blog.view_post`.
|
|
5
|
+
*/
|
|
6
|
+
definePageMeta({ layout: 'admin' })
|
|
7
|
+
|
|
8
|
+
const { t, n } = useI18n()
|
|
9
|
+
const { breadcrumbs } = useAdminPage()
|
|
10
|
+
|
|
11
|
+
const { data, error } = await useFetch('/api/blog/insights')
|
|
12
|
+
const maxComments = computed(() => Math.max(1, ...(data.value?.topPosts ?? []).map(p => p.comments)))
|
|
13
|
+
</script>
|
|
14
|
+
|
|
15
|
+
<template>
|
|
16
|
+
<UDashboardPanel id="blog-insights">
|
|
17
|
+
<template #header>
|
|
18
|
+
<AdminNavbar :breadcrumbs="breadcrumbs" />
|
|
19
|
+
</template>
|
|
20
|
+
|
|
21
|
+
<template #body>
|
|
22
|
+
<div class="mx-auto grid w-full max-w-5xl gap-6 lg:grid-cols-2">
|
|
23
|
+
<UAlert v-if="error" color="error" variant="subtle" icon="i-lucide-circle-alert" :title="t('blog.admin.insightsFailed')" class="lg:col-span-2" />
|
|
24
|
+
|
|
25
|
+
<UCard :ui="{ header: 'py-3 sm:px-5', body: 'sm:p-5' }">
|
|
26
|
+
<template #header>
|
|
27
|
+
<h2 class="text-sm font-semibold text-highlighted">{{ t('blog.admin.mostCommented') }}</h2>
|
|
28
|
+
</template>
|
|
29
|
+
<ul v-if="data?.topPosts.length" class="space-y-3">
|
|
30
|
+
<li v-for="item in data.topPosts" :key="item.id" class="space-y-1">
|
|
31
|
+
<div class="flex items-baseline justify-between gap-3 text-sm">
|
|
32
|
+
<NuxtLink :to="`/admin/blog_post/${item.id}`" class="truncate text-highlighted hover:text-primary">{{ item.title }}</NuxtLink>
|
|
33
|
+
<span class="shrink-0 text-muted tabular-nums">{{ n(item.comments) }}</span>
|
|
34
|
+
</div>
|
|
35
|
+
<UProgress :model-value="item.comments" :max="maxComments" size="xs" />
|
|
36
|
+
</li>
|
|
37
|
+
</ul>
|
|
38
|
+
<p v-else class="text-sm text-muted">{{ t('blog.admin.noPosts') }}</p>
|
|
39
|
+
</UCard>
|
|
40
|
+
|
|
41
|
+
<UCard :ui="{ header: 'py-3 sm:px-5', body: 'p-0 sm:p-0' }">
|
|
42
|
+
<template #header>
|
|
43
|
+
<h2 class="text-sm font-semibold text-highlighted">{{ t('blog.admin.postsPerCategory') }}</h2>
|
|
44
|
+
</template>
|
|
45
|
+
<ul v-if="data?.categories.length" class="divide-y divide-default">
|
|
46
|
+
<li v-for="item in data.categories" :key="item.id" class="flex items-center justify-between gap-3 px-4 py-2.5 text-sm sm:px-5">
|
|
47
|
+
<NuxtLink :to="`/admin/blog_post?f.categoryId=${item.id}`" class="truncate text-highlighted hover:text-primary">{{ item.name }}</NuxtLink>
|
|
48
|
+
<UBadge color="neutral" variant="subtle" :label="n(item.posts)" />
|
|
49
|
+
</li>
|
|
50
|
+
</ul>
|
|
51
|
+
<p v-else class="px-4 py-3 text-sm text-muted sm:px-5">{{ t('blog.admin.noCategories') }}</p>
|
|
52
|
+
</UCard>
|
|
53
|
+
</div>
|
|
54
|
+
</template>
|
|
55
|
+
</UDashboardPanel>
|
|
56
|
+
</template>
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
"groups": {
|
|
4
4
|
"blog": "Blog"
|
|
5
5
|
},
|
|
6
|
+
"adminPages": {
|
|
7
|
+
"blog_insights": "Auswertung"
|
|
8
|
+
},
|
|
9
|
+
"dashboardCards": {
|
|
10
|
+
"blog_stats": "Blog"
|
|
11
|
+
},
|
|
6
12
|
"models": {
|
|
7
13
|
"blog_category": {
|
|
8
14
|
"label": "Kategorie",
|
|
@@ -34,7 +40,8 @@
|
|
|
34
40
|
"categoryId": "Kategorie",
|
|
35
41
|
"authorId": "Autor",
|
|
36
42
|
"createdAt": "Erstellt am",
|
|
37
|
-
"updatedAt": "Aktualisiert am"
|
|
43
|
+
"updatedAt": "Aktualisiert am",
|
|
44
|
+
"deletedAt": "Gelöscht am"
|
|
38
45
|
},
|
|
39
46
|
"help": {
|
|
40
47
|
"slug": "Wird in der URL des Beitrags verwendet. Beim Anlegen aus dem Titel übernommen.",
|
|
@@ -67,6 +74,12 @@
|
|
|
67
74
|
"label": "Veröffentlichung aufheben",
|
|
68
75
|
"confirm": "Die ausgewählten Beiträge von der Website nehmen?"
|
|
69
76
|
}
|
|
77
|
+
},
|
|
78
|
+
"columns": {
|
|
79
|
+
"comments": "Kommentare"
|
|
80
|
+
},
|
|
81
|
+
"panels": {
|
|
82
|
+
"recent_comments": "Neueste Kommentare"
|
|
70
83
|
}
|
|
71
84
|
},
|
|
72
85
|
"blog_tag": {
|
|
@@ -135,6 +148,21 @@
|
|
|
135
148
|
"speed": "Ihre Lesegeschwindigkeit (Wörter pro Minute)",
|
|
136
149
|
"speedHelp": "Wird in diesem Browser gespeichert."
|
|
137
150
|
},
|
|
138
|
-
"live": "Live"
|
|
151
|
+
"live": "Live",
|
|
152
|
+
"admin": {
|
|
153
|
+
"posts": "Beiträge",
|
|
154
|
+
"comments": "Kommentare",
|
|
155
|
+
"published": "{count} veröffentlicht",
|
|
156
|
+
"pending": "{count} warten auf Freigabe",
|
|
157
|
+
"commentCounts": "{approved} freigegebene, {pending} wartende Kommentare",
|
|
158
|
+
"wordCount": "{words} Wörter · etwa {minutes} Min. Lesezeit",
|
|
159
|
+
"commentsUnavailable": "Du darfst keine Kommentare sehen.",
|
|
160
|
+
"allComments": "Alle {count} Kommentare",
|
|
161
|
+
"insightsFailed": "Die Auswertung konnte nicht geladen werden",
|
|
162
|
+
"mostCommented": "Meistkommentierte Beiträge",
|
|
163
|
+
"postsPerCategory": "Beiträge pro Kategorie",
|
|
164
|
+
"noPosts": "Noch keine Beiträge.",
|
|
165
|
+
"noCategories": "Noch keine Kategorien."
|
|
166
|
+
}
|
|
139
167
|
}
|
|
140
168
|
}
|
|
@@ -28,6 +28,21 @@
|
|
|
28
28
|
"speed": "Your reading speed (words per minute)",
|
|
29
29
|
"speedHelp": "Saved in this browser."
|
|
30
30
|
},
|
|
31
|
-
"live": "Live"
|
|
31
|
+
"live": "Live",
|
|
32
|
+
"admin": {
|
|
33
|
+
"posts": "Posts",
|
|
34
|
+
"comments": "Comments",
|
|
35
|
+
"published": "{count} published",
|
|
36
|
+
"pending": "{count} awaiting moderation",
|
|
37
|
+
"commentCounts": "{approved} approved, {pending} pending comments",
|
|
38
|
+
"wordCount": "{words} words · about {minutes} min to read",
|
|
39
|
+
"commentsUnavailable": "You may not view comments.",
|
|
40
|
+
"allComments": "All {count} comments",
|
|
41
|
+
"insightsFailed": "Could not load the insights",
|
|
42
|
+
"mostCommented": "Most commented posts",
|
|
43
|
+
"postsPerCategory": "Posts per category",
|
|
44
|
+
"noPosts": "No posts yet.",
|
|
45
|
+
"noCategories": "No categories yet."
|
|
46
|
+
}
|
|
32
47
|
}
|
|
33
48
|
}
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
"groups": {
|
|
4
4
|
"blog": "Blog"
|
|
5
5
|
},
|
|
6
|
+
"adminPages": {
|
|
7
|
+
"blog_insights": "Estadísticas"
|
|
8
|
+
},
|
|
9
|
+
"dashboardCards": {
|
|
10
|
+
"blog_stats": "Blog"
|
|
11
|
+
},
|
|
6
12
|
"models": {
|
|
7
13
|
"blog_category": {
|
|
8
14
|
"label": "Categoría",
|
|
@@ -34,7 +40,8 @@
|
|
|
34
40
|
"categoryId": "Categoría",
|
|
35
41
|
"authorId": "Autor",
|
|
36
42
|
"createdAt": "Creada el",
|
|
37
|
-
"updatedAt": "Actualizada el"
|
|
43
|
+
"updatedAt": "Actualizada el",
|
|
44
|
+
"deletedAt": "Eliminada el"
|
|
38
45
|
},
|
|
39
46
|
"help": {
|
|
40
47
|
"slug": "Se usa en la URL de la publicación. Se rellena a partir del título al crearla.",
|
|
@@ -67,6 +74,12 @@
|
|
|
67
74
|
"label": "Despublicar selección",
|
|
68
75
|
"confirm": "¿Retirar del sitio las publicaciones seleccionadas?"
|
|
69
76
|
}
|
|
77
|
+
},
|
|
78
|
+
"columns": {
|
|
79
|
+
"comments": "Comentarios"
|
|
80
|
+
},
|
|
81
|
+
"panels": {
|
|
82
|
+
"recent_comments": "Comentarios recientes"
|
|
70
83
|
}
|
|
71
84
|
},
|
|
72
85
|
"blog_tag": {
|
|
@@ -135,6 +148,21 @@
|
|
|
135
148
|
"speed": "Tu velocidad de lectura (palabras por minuto)",
|
|
136
149
|
"speedHelp": "Se guarda en este navegador."
|
|
137
150
|
},
|
|
138
|
-
"live": "En vivo"
|
|
151
|
+
"live": "En vivo",
|
|
152
|
+
"admin": {
|
|
153
|
+
"posts": "Entradas",
|
|
154
|
+
"comments": "Comentarios",
|
|
155
|
+
"published": "{count} publicadas",
|
|
156
|
+
"pending": "{count} pendientes de moderación",
|
|
157
|
+
"commentCounts": "{approved} comentarios aprobados, {pending} pendientes",
|
|
158
|
+
"wordCount": "{words} palabras · unos {minutes} min de lectura",
|
|
159
|
+
"commentsUnavailable": "No puedes ver los comentarios.",
|
|
160
|
+
"allComments": "Los {count} comentarios",
|
|
161
|
+
"insightsFailed": "No se pudieron cargar las estadísticas",
|
|
162
|
+
"mostCommented": "Entradas más comentadas",
|
|
163
|
+
"postsPerCategory": "Entradas por categoría",
|
|
164
|
+
"noPosts": "Aún no hay entradas.",
|
|
165
|
+
"noCategories": "Aún no hay categorías."
|
|
166
|
+
}
|
|
139
167
|
}
|
|
140
168
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { count, desc, eq } from 'drizzle-orm'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Data for the admin's Insights page (app/pages/admin/blog-insights.vue): the most commented posts
|
|
5
|
+
* and posts per category. The page is linked only for `blog.view_post`; the endpoint checks it too.
|
|
6
|
+
*/
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
await requirePermission(event, 'blog.view_post')
|
|
9
|
+
const db = useDB()
|
|
10
|
+
const { post, comment, category } = tables
|
|
11
|
+
const [topPosts, categories] = await Promise.all([
|
|
12
|
+
db.select({ id: post.id, title: post.title, comments: count(comment.id) })
|
|
13
|
+
.from(post)
|
|
14
|
+
.leftJoin(comment, eq(comment.postId, post.id))
|
|
15
|
+
.groupBy(post.id)
|
|
16
|
+
.orderBy(desc(count(comment.id)), desc(post.id))
|
|
17
|
+
.limit(5),
|
|
18
|
+
db.select({ id: category.id, name: category.name, posts: count(post.id) })
|
|
19
|
+
.from(category)
|
|
20
|
+
.leftJoin(post, eq(post.categoryId, category.id))
|
|
21
|
+
.groupBy(category.id)
|
|
22
|
+
.orderBy(desc(count(post.id)), category.name),
|
|
23
|
+
])
|
|
24
|
+
return { topPosts, categories }
|
|
25
|
+
})
|
|
@@ -4,7 +4,7 @@ import { and, eq } from 'drizzle-orm'
|
|
|
4
4
|
export default defineEventHandler(async (event) => {
|
|
5
5
|
const slug = getRouterParam(event, 'slug') ?? ''
|
|
6
6
|
const found = await useDB().query.post.findFirst({
|
|
7
|
-
where: and(eq(tables.post.slug, slug), eq(tables.post.published, true)),
|
|
7
|
+
where: and(eq(tables.post.slug, slug), eq(tables.post.published, true), notDeletedWhere(tables.post)),
|
|
8
8
|
with: {
|
|
9
9
|
category: { columns: { id: true, name: true, slug: true } },
|
|
10
10
|
author: { columns: { id: true, name: true } },
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { desc, eq } from 'drizzle-orm'
|
|
1
|
+
import { and, desc, eq } from 'drizzle-orm'
|
|
2
2
|
|
|
3
3
|
/** Published posts with category + author, via the merged, typed schema. */
|
|
4
4
|
export default defineEventHandler(async () => {
|
|
5
5
|
const db = useDB()
|
|
6
6
|
return db.query.post.findMany({
|
|
7
|
-
where: eq(tables.post.published, true),
|
|
7
|
+
where: and(eq(tables.post.published, true), notDeletedWhere(tables.post)),
|
|
8
8
|
orderBy: desc(tables.post.publishedAt),
|
|
9
9
|
with: {
|
|
10
10
|
category: { columns: { id: true, name: true, slug: true } },
|
|
@@ -1,25 +1,36 @@
|
|
|
1
|
+
import { defineEndpoint, z } from '@knit-framework/core/endpoints'
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* `POST { postId }`: enqueues the `blog.word-count` task and flashes the outcome (a toast on the
|
|
3
5
|
* next page, or right away via `useFlash().check()`). With the immediate backend the result is ready now.
|
|
6
|
+
*
|
|
7
|
+
* `defineEndpoint` checks the permission, validates the body (422 with `data.issues` otherwise)
|
|
8
|
+
* and lists the route in /api/r/openapi.json.
|
|
4
9
|
*/
|
|
5
|
-
export default
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
10
|
+
export default defineEndpoint({
|
|
11
|
+
summary: 'Count the words in a post',
|
|
12
|
+
description: 'Enqueues the `blog.word-count` task. With the immediate task backend, the result is in the response.',
|
|
13
|
+
permission: 'authenticated',
|
|
14
|
+
body: z.object({ postId: z.coerce.number().int().positive() }),
|
|
15
|
+
response: z.object({
|
|
16
|
+
id: z.string().nullable().describe('Queue row id (null with the immediate backend).'),
|
|
17
|
+
status: z.enum(['pending', 'running', 'succeeded', 'failed']),
|
|
18
|
+
result: z.object({ postId: z.number(), title: z.string(), words: z.number() }).nullable(),
|
|
19
|
+
}),
|
|
20
|
+
handler: async ({ event, body }) => {
|
|
21
|
+
const task = await enqueue('blog.word-count', { postId: body.postId })
|
|
22
|
+
// `task.result` is typed from the task's `run()` (see server/tasks/blog.ts).
|
|
23
|
+
if (task.status === 'succeeded' && task.result) {
|
|
24
|
+
const { words, title } = task.result
|
|
25
|
+
flash(event, { type: 'success', title: `${intcomma(words)} word${pluralize(words)}`, description: `in “${title}”` })
|
|
26
|
+
}
|
|
27
|
+
else if (task.status === 'failed') {
|
|
28
|
+
const description = task.error?.split('\n')[0]
|
|
29
|
+
flash(event, { type: 'error', title: 'Word count failed', ...(description !== undefined ? { description } : {}) })
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
flash(event, { type: 'info', title: 'Word count queued', description: `Task ${task.id}` })
|
|
33
|
+
}
|
|
34
|
+
return { id: task.id, status: task.status, result: task.result ?? null }
|
|
35
|
+
},
|
|
25
36
|
})
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { eq, or, relations } from 'drizzle-orm'
|
|
1
|
+
import { eq, or, relations, sql } from 'drizzle-orm'
|
|
2
2
|
import { boolean, index, integer, pgTable, serial, text, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core'
|
|
3
3
|
import { fileColumn } from '@knit-framework/core/fields'
|
|
4
4
|
import { defineModelMeta, isRowOwner, signals, ValidationError } from '@knit-framework/core/models'
|
|
5
5
|
import { broadcastModel } from '@knit-framework/core/realtime'
|
|
6
|
-
import { user } from '@knit-framework/core/schema'
|
|
6
|
+
import { searchIndex, searchVector, softDeleteColumn, user } from '@knit-framework/core/schema'
|
|
7
7
|
|
|
8
8
|
export const category = pgTable('blog_category', {
|
|
9
9
|
id: serial('id').primaryKey(),
|
|
@@ -18,7 +18,8 @@ export const post = pgTable(
|
|
|
18
18
|
{
|
|
19
19
|
id: serial('id').primaryKey(),
|
|
20
20
|
title: varchar('title', { length: 200 }).notNull(),
|
|
21
|
-
|
|
21
|
+
// Unique among live posts (the index below): a post in the trash doesn't block its slug.
|
|
22
|
+
slug: varchar('slug', { length: 220 }).notNull(),
|
|
22
23
|
body: text('body').notNull().default(''),
|
|
23
24
|
/** Optional cover image; the admin shows an upload widget. */
|
|
24
25
|
cover: fileColumn('cover'),
|
|
@@ -31,8 +32,16 @@ export const post = pgTable(
|
|
|
31
32
|
.notNull()
|
|
32
33
|
.defaultNow()
|
|
33
34
|
.$onUpdate(() => new Date()),
|
|
35
|
+
/** Set while the post is in the trash (`softDelete` below). */
|
|
36
|
+
deletedAt: softDeleteColumn(),
|
|
37
|
+
/** Full-text search over the title (counts most) and the body, kept up to date by the database. */
|
|
38
|
+
search: searchVector('search', { title: 'A', body: 'B' }),
|
|
34
39
|
},
|
|
35
|
-
t => [
|
|
40
|
+
t => [
|
|
41
|
+
index('blog_post_category_id_idx').on(t.categoryId),
|
|
42
|
+
uniqueIndex('blog_post_slug_live_idx').on(t.slug).where(sql`deleted_at is null`),
|
|
43
|
+
searchIndex(t.search),
|
|
44
|
+
],
|
|
36
45
|
)
|
|
37
46
|
|
|
38
47
|
export const tag = pgTable('blog_tag', {
|
|
@@ -113,6 +122,11 @@ defineModelMeta(category, {
|
|
|
113
122
|
|
|
114
123
|
defineModelMeta(post, {
|
|
115
124
|
ordering: ['-createdAt'],
|
|
125
|
+
// Deleting moves a post to the trash (restore it from the admin); every change is recorded, field by
|
|
126
|
+
// field, in the change history; `useModel(post).search()` and `?q=` use the search vector.
|
|
127
|
+
softDelete: 'deletedAt',
|
|
128
|
+
history: true,
|
|
129
|
+
search: 'search',
|
|
116
130
|
// Row-level permissions, respected by the admin, the posts API and broadcasts: editors change and
|
|
117
131
|
// delete their own posts; `blog.change_any_post` (registered in admin.ts) lifts that. A new post's
|
|
118
132
|
// author is the user who creates it. No `scope`: everyone may still read every post they could before.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { desc, eq } from 'drizzle-orm'
|
|
1
|
+
import { and, desc, eq } from 'drizzle-orm'
|
|
2
2
|
|
|
3
3
|
/** Shared by the RSS (`/blog/feed.xml`) and Atom (`/blog/atom.xml`) routes. */
|
|
4
4
|
export const blogFeed = {
|
|
@@ -8,7 +8,7 @@ export const blogFeed = {
|
|
|
8
8
|
language: 'en',
|
|
9
9
|
async items() {
|
|
10
10
|
const posts = await useDB().query.post.findMany({
|
|
11
|
-
where: eq(tables.post.published, true),
|
|
11
|
+
where: and(eq(tables.post.published, true), notDeletedWhere(tables.post)),
|
|
12
12
|
orderBy: desc(tables.post.publishedAt),
|
|
13
13
|
limit: 20,
|
|
14
14
|
with: { author: { columns: { name: true } }, category: { columns: { name: true } } },
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { desc, eq } from 'drizzle-orm'
|
|
1
|
+
import { and, desc, eq } from 'drizzle-orm'
|
|
2
2
|
|
|
3
3
|
/** Blog section of `/sitemap.xml`: the index plus every published post. */
|
|
4
4
|
export default defineSitemap(async () => {
|
|
5
5
|
const posts = await useDB().query.post.findMany({
|
|
6
|
-
where: eq(tables.post.published, true),
|
|
6
|
+
where: and(eq(tables.post.published, true), notDeletedWhere(tables.post)),
|
|
7
7
|
orderBy: desc(tables.post.publishedAt),
|
|
8
8
|
columns: { slug: true, updatedAt: true },
|
|
9
9
|
})
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* pnpm manage runtask blog.word-count --payload '{"postId":1}'
|
|
7
7
|
*/
|
|
8
8
|
import { count, eq } from 'drizzle-orm'
|
|
9
|
+
import { notDeletedWhere } from '@knit-framework/core/models'
|
|
9
10
|
import { defineTask } from '@knit-framework/core/tasks'
|
|
10
11
|
import { post } from '../database/schema'
|
|
11
12
|
|
|
@@ -38,6 +39,7 @@ export const blogStats = defineTask({
|
|
|
38
39
|
const rows = await ctx.db
|
|
39
40
|
.select({ published: post.published, total: count() })
|
|
40
41
|
.from(post)
|
|
42
|
+
.where(notDeletedWhere(post))
|
|
41
43
|
.groupBy(post.published)
|
|
42
44
|
const stats = {
|
|
43
45
|
published: rows.find(r => r.published)?.total ?? 0,
|
package/template/versions.json
CHANGED