Skip to content

Commit 838254c

Browse files
committed
Schema and shell for search, notifications and reports
- French full-text GIN indexes on articles, threads and discussions - notifications and reports tables with typed enums, models - Unread notifications count shared with every page; search and notifications entries in the navigation (theme toggle moves into the mobile menu on small screens)
1 parent fb98a25 commit 838254c

14 files changed

Lines changed: 380 additions & 2 deletions

‎app/middleware/inertia_middleware.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ import UserTransformer from '#transformers/user_transformer'
44
import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware'
55
import { githubEnabled } from '#config/ally'
66
import env from '#start/env'
7+
import db from '@adonisjs/lucid/services/db'
78

89
export type ThemePreference = 'light' | 'dark' | 'system'
910

1011
export default class InertiaMiddleware extends BaseInertiaMiddleware {
11-
share(ctx: HttpContext) {
12+
async share(ctx: HttpContext) {
1213
/**
1314
* The share method is called everytime an Inertia page is rendered. In
1415
* certain cases, a page may get rendered before the session middleware
@@ -22,6 +23,16 @@ export default class InertiaMiddleware extends BaseInertiaMiddleware {
2223
const cookie = request?.plainCookie('app_theme', { encoded: false })
2324
const theme: ThemePreference = cookie === 'light' || cookie === 'dark' ? cookie : 'system'
2425

26+
let unreadNotifications = 0
27+
if (auth?.user) {
28+
const [row] = await db
29+
.from('notifications')
30+
.where('user_id', auth.user.id)
31+
.whereNull('read_at')
32+
.count('* as total')
33+
unreadNotifications = Number(row?.total ?? 0)
34+
}
35+
2536
/**
2637
* Data shared with all Inertia pages. Make sure you are using
2738
* transformers for rich data-types like Models.
@@ -34,6 +45,7 @@ export default class InertiaMiddleware extends BaseInertiaMiddleware {
3445
preferences: ctx.inertia.always({ theme }),
3546
features: ctx.inertia.always({ github: githubEnabled() }),
3647
site: ctx.inertia.always({ url: env.get('APP_URL') }),
48+
unreadNotifications: ctx.inertia.always(unreadNotifications),
3749
}
3850
}
3951

‎app/models/notification.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { NotificationSchema } from '#database/schema'
2+
import { belongsTo } from '@adonisjs/lucid/orm'
3+
import type { BelongsTo } from '@adonisjs/lucid/types/relations'
4+
import User from '#models/user'
5+
import Thread from '#models/thread'
6+
import Discussion from '#models/discussion'
7+
import Article from '#models/article'
8+
import Reply from '#models/reply'
9+
10+
export type NotificationType = Notification['type']
11+
12+
export default class Notification extends NotificationSchema {
13+
@belongsTo(() => User)
14+
declare user: BelongsTo<typeof User>
15+
16+
@belongsTo(() => User, { foreignKey: 'actorId' })
17+
declare actor: BelongsTo<typeof User>
18+
19+
@belongsTo(() => Thread)
20+
declare thread: BelongsTo<typeof Thread>
21+
22+
@belongsTo(() => Discussion)
23+
declare discussion: BelongsTo<typeof Discussion>
24+
25+
@belongsTo(() => Article)
26+
declare article: BelongsTo<typeof Article>
27+
28+
@belongsTo(() => Reply)
29+
declare reply: BelongsTo<typeof Reply>
30+
31+
get isRead() {
32+
return this.readAt !== null
33+
}
34+
}

‎app/models/report.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { ReportSchema } from '#database/schema'
2+
import { belongsTo } from '@adonisjs/lucid/orm'
3+
import type { BelongsTo } from '@adonisjs/lucid/types/relations'
4+
import User from '#models/user'
5+
import Thread from '#models/thread'
6+
import Discussion from '#models/discussion'
7+
import Article from '#models/article'
8+
import Reply from '#models/reply'
9+
10+
export type ReportReason = Report['reason']
11+
export type ReportStatus = Report['status']
12+
13+
export default class Report extends ReportSchema {
14+
@belongsTo(() => User, { foreignKey: 'reporterId' })
15+
declare reporter: BelongsTo<typeof User>
16+
17+
@belongsTo(() => User, { foreignKey: 'resolvedById' })
18+
declare resolvedBy: BelongsTo<typeof User>
19+
20+
@belongsTo(() => Article)
21+
declare article: BelongsTo<typeof Article>
22+
23+
@belongsTo(() => Thread)
24+
declare thread: BelongsTo<typeof Thread>
25+
26+
@belongsTo(() => Discussion)
27+
declare discussion: BelongsTo<typeof Discussion>
28+
29+
@belongsTo(() => Reply)
30+
declare reply: BelongsTo<typeof Reply>
31+
}

‎app/services/search_documents.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* Full-text "documents" (French stemming) indexed by GIN indexes. Search
3+
* queries must use these exact expressions for PostgreSQL to use the index.
4+
* Title words weigh more (A) than the body (B/C).
5+
*/
6+
export const SEARCH_DOCUMENTS = {
7+
articles: `(setweight(to_tsvector('french', coalesce(title, '')), 'A') || setweight(to_tsvector('french', coalesce(excerpt, '')), 'B') || setweight(to_tsvector('french', body), 'C'))`,
8+
threads: `(setweight(to_tsvector('french', coalesce(title, '')), 'A') || setweight(to_tsvector('french', body), 'C'))`,
9+
discussions: `(setweight(to_tsvector('french', coalesce(title, '')), 'A') || setweight(to_tsvector('french', body), 'C'))`,
10+
} as const
11+
12+
export type SearchableTable = keyof typeof SEARCH_DOCUMENTS
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { BaseSchema } from '@adonisjs/lucid/schema'
2+
3+
/**
4+
* In-app notifications: someone answered your question, commented your
5+
* article, accepted your answer… The subject columns point at the content
6+
* (cascade: notifications disappear with it).
7+
*/
8+
export default class extends BaseSchema {
9+
protected tableName = 'notifications'
10+
11+
async up() {
12+
this.schema.createTable(this.tableName, (table) => {
13+
table.increments('id').notNullable()
14+
table
15+
.integer('user_id')
16+
.notNullable()
17+
.unsigned()
18+
.references('id')
19+
.inTable('users')
20+
.onDelete('CASCADE')
21+
table
22+
.integer('actor_id')
23+
.nullable()
24+
.unsigned()
25+
.references('id')
26+
.inTable('users')
27+
.onDelete('CASCADE')
28+
table.string('type', 40).notNullable()
29+
table
30+
.integer('thread_id')
31+
.nullable()
32+
.unsigned()
33+
.references('id')
34+
.inTable('threads')
35+
.onDelete('CASCADE')
36+
table
37+
.integer('discussion_id')
38+
.nullable()
39+
.unsigned()
40+
.references('id')
41+
.inTable('discussions')
42+
.onDelete('CASCADE')
43+
table
44+
.integer('article_id')
45+
.nullable()
46+
.unsigned()
47+
.references('id')
48+
.inTable('articles')
49+
.onDelete('CASCADE')
50+
table
51+
.integer('reply_id')
52+
.nullable()
53+
.unsigned()
54+
.references('id')
55+
.inTable('replies')
56+
.onDelete('CASCADE')
57+
table.timestamp('read_at', { useTz: true }).nullable()
58+
table.timestamp('created_at', { useTz: true }).notNullable()
59+
60+
table.index(['user_id', 'created_at'])
61+
table.index(['user_id', 'read_at'])
62+
})
63+
}
64+
65+
async down() {
66+
this.schema.dropTable(this.tableName)
67+
}
68+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { BaseSchema } from '@adonisjs/lucid/schema'
2+
3+
/**
4+
* Members flag content for the moderators. Exactly one target is set.
5+
*/
6+
export default class extends BaseSchema {
7+
protected tableName = 'reports'
8+
9+
async up() {
10+
this.schema.createTable(this.tableName, (table) => {
11+
table.increments('id').notNullable()
12+
table
13+
.integer('reporter_id')
14+
.notNullable()
15+
.unsigned()
16+
.references('id')
17+
.inTable('users')
18+
.onDelete('CASCADE')
19+
table
20+
.integer('article_id')
21+
.nullable()
22+
.unsigned()
23+
.references('id')
24+
.inTable('articles')
25+
.onDelete('CASCADE')
26+
table
27+
.integer('thread_id')
28+
.nullable()
29+
.unsigned()
30+
.references('id')
31+
.inTable('threads')
32+
.onDelete('CASCADE')
33+
table
34+
.integer('discussion_id')
35+
.nullable()
36+
.unsigned()
37+
.references('id')
38+
.inTable('discussions')
39+
.onDelete('CASCADE')
40+
table
41+
.integer('reply_id')
42+
.nullable()
43+
.unsigned()
44+
.references('id')
45+
.inTable('replies')
46+
.onDelete('CASCADE')
47+
table.string('reason', 40).notNullable()
48+
table.string('details', 500).nullable()
49+
table.string('status', 20).notNullable().defaultTo('open')
50+
table
51+
.integer('resolved_by_id')
52+
.nullable()
53+
.unsigned()
54+
.references('id')
55+
.inTable('users')
56+
.onDelete('SET NULL')
57+
table.timestamp('resolved_at', { useTz: true }).nullable()
58+
table.timestamp('created_at', { useTz: true }).notNullable()
59+
table.timestamp('updated_at', { useTz: true }).nullable()
60+
61+
table.index(['status', 'created_at'])
62+
})
63+
64+
this.schema.raw(
65+
'ALTER TABLE reports ADD CONSTRAINT reports_single_target CHECK (num_nonnulls(article_id, thread_id, discussion_id, reply_id) = 1)'
66+
)
67+
}
68+
69+
async down() {
70+
this.schema.dropTable(this.tableName)
71+
}
72+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { BaseSchema } from '@adonisjs/lucid/schema'
2+
import { SEARCH_DOCUMENTS } from '#services/search_documents'
3+
4+
/**
5+
* French full-text indexes. The expressions come from
6+
* app/services/search_documents.ts so queries always match the index.
7+
*/
8+
export default class extends BaseSchema {
9+
async up() {
10+
for (const [table, document] of Object.entries(SEARCH_DOCUMENTS)) {
11+
this.schema.raw(`CREATE INDEX ${table}_search_idx ON ${table} USING GIN (${document})`)
12+
}
13+
}
14+
15+
async down() {
16+
for (const table of Object.keys(SEARCH_DOCUMENTS)) {
17+
this.schema.raw(`DROP INDEX IF EXISTS ${table}_search_idx`)
18+
}
19+
}
20+
}

‎database/schema.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,31 @@ export class LikeSchema extends BaseModel {
123123
declare userId: number
124124
}
125125

126+
export class NotificationSchema extends BaseModel {
127+
static $columns = ['actorId', 'articleId', 'createdAt', 'discussionId', 'id', 'readAt', 'replyId', 'threadId', 'type', 'userId'] as const
128+
$columns = NotificationSchema.$columns
129+
@column()
130+
declare actorId: number | null
131+
@column()
132+
declare articleId: number | null
133+
@column.dateTime({ autoCreate: true })
134+
declare createdAt: DateTime
135+
@column()
136+
declare discussionId: number | null
137+
@column({ isPrimary: true })
138+
declare id: number
139+
@column.dateTime()
140+
declare readAt: DateTime | null
141+
@column()
142+
declare replyId: number | null
143+
@column()
144+
declare threadId: number | null
145+
@column()
146+
declare type: 'thread_reply' | 'discussion_reply' | 'article_comment' | 'solution_accepted'
147+
@column()
148+
declare userId: number
149+
}
150+
126151
export class RateLimitSchema extends BaseModel {
127152
static $columns = ['expire', 'key', 'points'] as const
128153
$columns = RateLimitSchema.$columns
@@ -174,6 +199,37 @@ export class ReplySchema extends BaseModel {
174199
declare userId: number
175200
}
176201

202+
export class ReportSchema extends BaseModel {
203+
static $columns = ['articleId', 'createdAt', 'details', 'discussionId', 'id', 'reason', 'replyId', 'reporterId', 'resolvedAt', 'resolvedById', 'status', 'threadId', 'updatedAt'] as const
204+
$columns = ReportSchema.$columns
205+
@column()
206+
declare articleId: number | null
207+
@column.dateTime({ autoCreate: true })
208+
declare createdAt: DateTime
209+
@column()
210+
declare details: string | null
211+
@column()
212+
declare discussionId: number | null
213+
@column({ isPrimary: true })
214+
declare id: number
215+
@column()
216+
declare reason: 'spam' | 'abuse' | 'off_topic' | 'other'
217+
@column()
218+
declare replyId: number | null
219+
@column()
220+
declare reporterId: number
221+
@column.dateTime()
222+
declare resolvedAt: DateTime | null
223+
@column()
224+
declare resolvedById: number | null
225+
@column()
226+
declare status: 'open' | 'resolved' | 'dismissed'
227+
@column()
228+
declare threadId: number | null
229+
@column.dateTime({ autoCreate: true, autoUpdate: true })
230+
declare updatedAt: DateTime | null
231+
}
232+
177233
export class TagSchema extends BaseModel {
178234
static $columns = ['createdAt', 'description', 'id', 'name', 'slug', 'updatedAt'] as const
179235
$columns = TagSchema.$columns

‎database/schema_rules.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,26 @@ import { type SchemaRules } from '@adonisjs/lucid/types/schema_generator'
22

33
export default {
44
tables: {
5+
notifications: {
6+
columns: {
7+
type: {
8+
tsType: `'thread_reply' | 'discussion_reply' | 'article_comment' | 'solution_accepted'`,
9+
decorators: [{ name: '@column' }],
10+
},
11+
},
12+
},
13+
reports: {
14+
columns: {
15+
reason: {
16+
tsType: `'spam' | 'abuse' | 'off_topic' | 'other'`,
17+
decorators: [{ name: '@column' }],
18+
},
19+
status: {
20+
tsType: `'open' | 'resolved' | 'dismissed'`,
21+
decorators: [{ name: '@column' }],
22+
},
23+
},
24+
},
525
users: {
626
columns: {
727
role: {

0 commit comments

Comments
 (0)