@molecule/api-resource-article 0.0.0-stage → 1.0.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/dist/routes.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Article route definitions.
3
+ *
4
+ * Declarative routing — mlcl inject reads these to generate the Express
5
+ * router. `feed` and `tags` come before `:slug`, and those two words are never
6
+ * given to an article as its slug.
7
+ *
8
+ * @module
9
+ */
10
+ /**
11
+ * Routes for articles, the feed, tags and favorites.
12
+ */
13
+ export const routes = [
14
+ { method: 'post', path: '/articles', handler: 'create', middlewares: ['authenticate'] },
15
+ { method: 'get', path: '/articles', handler: 'list' },
16
+ { method: 'get', path: '/articles/feed', handler: 'feed', middlewares: ['authenticate'] },
17
+ { method: 'get', path: '/articles/tags', handler: 'tags' },
18
+ { method: 'get', path: '/articles/:slug', handler: 'read' },
19
+ { method: 'put', path: '/articles/:slug', handler: 'update', middlewares: ['authenticate'] },
20
+ { method: 'delete', path: '/articles/:slug', handler: 'del', middlewares: ['authenticate'] },
21
+ {
22
+ method: 'post',
23
+ path: '/articles/:slug/favorite',
24
+ handler: 'favorite',
25
+ middlewares: ['authenticate'],
26
+ },
27
+ {
28
+ method: 'delete',
29
+ path: '/articles/:slug/favorite',
30
+ handler: 'unfavorite',
31
+ middlewares: ['authenticate'],
32
+ },
33
+ ];
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Article business logic.
3
+ *
4
+ * Every read and write goes through the abstract DataStore
5
+ * (`@molecule/api-database`). Favorites are `favorite` reactions
6
+ * (`@molecule/api-resource-reaction`, resource type {@link ARTICLE_RESOURCE_TYPE})
7
+ * and the feed reads who a user follows from `@molecule/api-resource-follow`'s
8
+ * `follows` table, so an app that already uses those packages sees the same
9
+ * favorites and follows everywhere.
10
+ *
11
+ * @module
12
+ */
13
+ import type { Article, ArticleRow, CreateArticleInput, ListArticlesOptions, PaginatedArticles, TagCount, UpdateArticleInput } from './types.js';
14
+ /** The resource type favorites and comments on articles are stored under. */
15
+ export declare const ARTICLE_RESOURCE_TYPE = "article";
16
+ /** The reaction type a favorite is stored as. */
17
+ export declare const FAVORITE_REACTION = "favorite";
18
+ /**
19
+ * Slugs the routes use for themselves (`/articles/feed`, `/articles/tags`): an
20
+ * article titled "Feed" gets `feed-2`, or its page would be unreachable.
21
+ */
22
+ export declare const RESERVED_ARTICLE_SLUGS: ReadonlySet<string>;
23
+ /** Largest page a list returns. */
24
+ export declare const MAX_ARTICLES_PAGE = 100;
25
+ /**
26
+ * Turn stored rows into {@link Article}s: decoded tags, favorite counts and the
27
+ * viewer's own favorites, in two queries for the whole page.
28
+ *
29
+ * @param rows - Article rows.
30
+ * @param viewerId - The viewing user, if any.
31
+ * @returns The articles, in the order given.
32
+ */
33
+ export declare function hydrateArticles(rows: ArticleRow[], viewerId?: string): Promise<Article[]>;
34
+ /**
35
+ * Create an article with a unique slug derived from its title.
36
+ *
37
+ * @param authorId - The writing user.
38
+ * @param input - Title, body, optional description and tags.
39
+ * @returns The created article.
40
+ */
41
+ export declare function createArticle(authorId: string, input: CreateArticleInput): Promise<Article>;
42
+ /**
43
+ * The stored row for a slug.
44
+ *
45
+ * @param slug - The article slug.
46
+ * @returns The row, or null.
47
+ */
48
+ export declare function findArticleRow(slug: string): Promise<ArticleRow | null>;
49
+ /**
50
+ * An article by slug.
51
+ *
52
+ * @param slug - The article slug.
53
+ * @param viewerId - The viewing user, for `favorited`.
54
+ * @returns The article, or null.
55
+ */
56
+ export declare function getArticleBySlug(slug: string, viewerId?: string): Promise<Article | null>;
57
+ /**
58
+ * Articles newest first, filtered by tag, author and who favorited them.
59
+ *
60
+ * @param options - Filters, paging and the viewer.
61
+ * @returns A page of articles and the total matching.
62
+ */
63
+ export declare function listArticles(options?: ListArticlesOptions): Promise<PaginatedArticles>;
64
+ /**
65
+ * Articles by the users `userId` follows, newest first.
66
+ *
67
+ * @param userId - The reader.
68
+ * @param options - Paging.
69
+ * @returns A page of articles and the total.
70
+ */
71
+ export declare function getFeed(userId: string, options?: {
72
+ limit?: number;
73
+ offset?: number;
74
+ }): Promise<PaginatedArticles>;
75
+ /** The outcome of a change that only the author may make. */
76
+ export type AuthorChange<T> = {
77
+ status: 'ok';
78
+ article: T;
79
+ } | {
80
+ status: 'not_found';
81
+ } | {
82
+ status: 'forbidden';
83
+ };
84
+ /**
85
+ * Update an article. Only its author may; a changed title gives it a new slug.
86
+ *
87
+ * @param slug - The article slug.
88
+ * @param userId - The requesting user.
89
+ * @param input - The fields to change.
90
+ * @returns The updated article, or why not.
91
+ */
92
+ export declare function updateArticle(slug: string, userId: string, input: UpdateArticleInput): Promise<AuthorChange<Article>>;
93
+ /**
94
+ * Delete an article and its tags and favorites. Only its author may.
95
+ *
96
+ * @param slug - The article slug.
97
+ * @param userId - The requesting user.
98
+ * @returns Whether it was deleted, or why not.
99
+ */
100
+ export declare function deleteArticle(slug: string, userId: string): Promise<AuthorChange<true>>;
101
+ /**
102
+ * Favorite or unfavorite an article for a user (idempotent both ways).
103
+ *
104
+ * @param slug - The article slug.
105
+ * @param userId - The user.
106
+ * @param favorite - True to favorite, false to remove the favorite.
107
+ * @returns The article after the change, or null when there is no such article.
108
+ */
109
+ export declare function setFavorite(slug: string, userId: string, favorite: boolean): Promise<Article | null>;
110
+ /**
111
+ * Tags in use, most-used first.
112
+ *
113
+ * @param limit - How many to return (default 20).
114
+ * @returns Tags with their article counts.
115
+ */
116
+ export declare function popularTags(limit?: number): Promise<TagCount[]>;
117
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAcH,OAAO,KAAK,EACV,OAAO,EACP,UAAU,EACV,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,QAAQ,EACR,kBAAkB,EACnB,MAAM,YAAY,CAAA;AAOnB,6EAA6E;AAC7E,eAAO,MAAM,qBAAqB,YAAY,CAAA;AAE9C,iDAAiD;AACjD,eAAO,MAAM,iBAAiB,aAAa,CAAA;AAE3C;;;GAGG;AACH,eAAO,MAAM,sBAAsB,EAAE,WAAW,CAAC,MAAM,CAA6B,CAAA;AA6BpF,mCAAmC;AACnC,eAAO,MAAM,iBAAiB,MAAM,CAAA;AAyBpC;;;;;;;GAOG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CA6B/F;AAOD;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBjG;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAE7E;AAED;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAK/F;AAiCD;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAoBhG;AAED;;;;;;GAMG;AACH,wBAAsB,OAAO,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAChD,OAAO,CAAC,iBAAiB,CAAC,CAsB5B;AAED,6DAA6D;AAC7D,MAAM,MAAM,YAAY,CAAC,CAAC,IACxB;IAAE,MAAM,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,WAAW,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,WAAW,CAAA;CAAE,CAAA;AAElF;;;;;;;GAOG;AACH,wBAAsB,aAAa,CACjC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,kBAAkB,GACxB,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAkBhC;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAW7F;AAED;;;;;;;GAOG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,OAAO,GAChB,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,CAOzB;AAED;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAK,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAQjE"}
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Article business logic.
3
+ *
4
+ * Every read and write goes through the abstract DataStore
5
+ * (`@molecule/api-database`). Favorites are `favorite` reactions
6
+ * (`@molecule/api-resource-reaction`, resource type {@link ARTICLE_RESOURCE_TYPE})
7
+ * and the feed reads who a user follows from `@molecule/api-resource-follow`'s
8
+ * `follows` table, so an app that already uses those packages sees the same
9
+ * favorites and follows everywhere.
10
+ *
11
+ * @module
12
+ */
13
+ import { count, create as dbCreate, deleteById, deleteMany, findMany, findOne, updateById, } from '@molecule/api-database';
14
+ import { addReaction, removeReaction } from '@molecule/api-resource-reaction';
15
+ import { uniqueSlug } from '@molecule/api-slug';
16
+ const ARTICLES = 'articles';
17
+ const ARTICLE_TAGS = 'article_tags';
18
+ const REACTIONS = 'reactions';
19
+ const FOLLOWS = 'follows';
20
+ /** The resource type favorites and comments on articles are stored under. */
21
+ export const ARTICLE_RESOURCE_TYPE = 'article';
22
+ /** The reaction type a favorite is stored as. */
23
+ export const FAVORITE_REACTION = 'favorite';
24
+ /**
25
+ * Slugs the routes use for themselves (`/articles/feed`, `/articles/tags`): an
26
+ * article titled "Feed" gets `feed-2`, or its page would be unreachable.
27
+ */
28
+ export const RESERVED_ARTICLE_SLUGS = new Set(['feed', 'tags']);
29
+ /** A free slug for a title; `excludeId` lets an article keep its own on update. */
30
+ const articleSlug = (title, excludeId) => uniqueSlug(title, async (slug) => {
31
+ if (RESERVED_ARTICLE_SLUGS.has(slug))
32
+ return true;
33
+ const row = await findOne(ARTICLES, [
34
+ { field: 'slug', operator: '=', value: slug },
35
+ ]);
36
+ return row != null && row.id !== excludeId;
37
+ }, { fallback: 'article' });
38
+ let lastCreatedMs = 0;
39
+ /**
40
+ * A creation time later than every earlier one from this process: two
41
+ * articles created in the same millisecond must still sort newest first.
42
+ *
43
+ * @returns The ISO time.
44
+ */
45
+ const nextCreatedAt = () => {
46
+ lastCreatedMs = Math.max(Date.now(), lastCreatedMs + 1);
47
+ return new Date(lastCreatedMs).toISOString();
48
+ };
49
+ /** Largest page a list returns. */
50
+ export const MAX_ARTICLES_PAGE = 100;
51
+ const pageOf = (options) => ({
52
+ limit: Math.min(MAX_ARTICLES_PAGE, Math.max(1, Math.floor(options.limit ?? 20))),
53
+ offset: Math.max(0, Math.floor(options.offset ?? 0)),
54
+ });
55
+ const parseTags = (raw) => {
56
+ try {
57
+ const parsed = JSON.parse(raw);
58
+ return Array.isArray(parsed) ? parsed.filter((t) => typeof t === 'string') : [];
59
+ }
60
+ catch (_error) {
61
+ // A row written outside this package with a non-JSON tagList has no tags to show.
62
+ return [];
63
+ }
64
+ };
65
+ /** Distinct, trimmed tag names in the order given. */
66
+ const cleanTags = (tags) => [
67
+ ...new Set((tags ?? []).map((t) => t.trim()).filter(Boolean)),
68
+ ];
69
+ /**
70
+ * Turn stored rows into {@link Article}s: decoded tags, favorite counts and the
71
+ * viewer's own favorites, in two queries for the whole page.
72
+ *
73
+ * @param rows - Article rows.
74
+ * @param viewerId - The viewing user, if any.
75
+ * @returns The articles, in the order given.
76
+ */
77
+ export async function hydrateArticles(rows, viewerId) {
78
+ if (rows.length === 0)
79
+ return [];
80
+ const favorites = await findMany(REACTIONS, {
81
+ where: [
82
+ { field: 'resourceType', operator: '=', value: ARTICLE_RESOURCE_TYPE },
83
+ { field: 'type', operator: '=', value: FAVORITE_REACTION },
84
+ { field: 'resourceId', operator: 'in', value: rows.map((r) => r.id) },
85
+ ],
86
+ select: ['resourceId', 'userId'],
87
+ });
88
+ const counts = new Map();
89
+ const mine = new Set();
90
+ for (const f of favorites) {
91
+ counts.set(f.resourceId, (counts.get(f.resourceId) ?? 0) + 1);
92
+ if (viewerId && f.userId === viewerId)
93
+ mine.add(f.resourceId);
94
+ }
95
+ return rows.map((row) => ({
96
+ id: row.id,
97
+ slug: row.slug,
98
+ title: row.title,
99
+ description: row.description ?? '',
100
+ body: row.body,
101
+ tagList: parseTags(row.tagList),
102
+ authorId: row.authorId,
103
+ createdAt: row.createdAt,
104
+ updatedAt: row.updatedAt,
105
+ favoritesCount: counts.get(row.id) ?? 0,
106
+ favorited: mine.has(row.id),
107
+ }));
108
+ }
109
+ const writeTags = async (articleId, tags) => {
110
+ await deleteMany(ARTICLE_TAGS, [{ field: 'articleId', operator: '=', value: articleId }]);
111
+ for (const tag of tags)
112
+ await dbCreate(ARTICLE_TAGS, { articleId, tag });
113
+ };
114
+ /**
115
+ * Create an article with a unique slug derived from its title.
116
+ *
117
+ * @param authorId - The writing user.
118
+ * @param input - Title, body, optional description and tags.
119
+ * @returns The created article.
120
+ */
121
+ export async function createArticle(authorId, input) {
122
+ const slug = await articleSlug(input.title);
123
+ const tags = cleanTags(input.tagList);
124
+ // Written here rather than by the column default: SQLite's CURRENT_TIMESTAMP
125
+ // has whole seconds, so two articles from the same second tied and "newest
126
+ // first" came back in either order; this one is unique per process.
127
+ const now = nextCreatedAt();
128
+ const result = await dbCreate(ARTICLES, {
129
+ slug,
130
+ title: input.title,
131
+ description: input.description ?? '',
132
+ body: input.body,
133
+ tagList: JSON.stringify(tags),
134
+ authorId,
135
+ createdAt: now,
136
+ updatedAt: now,
137
+ });
138
+ const row = result.data;
139
+ await writeTags(row.id, tags);
140
+ const [article] = await hydrateArticles([row], authorId);
141
+ return article;
142
+ }
143
+ /**
144
+ * The stored row for a slug.
145
+ *
146
+ * @param slug - The article slug.
147
+ * @returns The row, or null.
148
+ */
149
+ export async function findArticleRow(slug) {
150
+ return findOne(ARTICLES, [{ field: 'slug', operator: '=', value: slug }]);
151
+ }
152
+ /**
153
+ * An article by slug.
154
+ *
155
+ * @param slug - The article slug.
156
+ * @param viewerId - The viewing user, for `favorited`.
157
+ * @returns The article, or null.
158
+ */
159
+ export async function getArticleBySlug(slug, viewerId) {
160
+ const row = await findArticleRow(slug);
161
+ if (!row)
162
+ return null;
163
+ const [article] = await hydrateArticles([row], viewerId);
164
+ return article;
165
+ }
166
+ /**
167
+ * Article ids matching the tag and favorited-by filters; `null` when neither
168
+ * filter is set (no restriction).
169
+ *
170
+ * @param options - The filters.
171
+ * @returns The allowed ids, or null.
172
+ */
173
+ async function filteredIds(options) {
174
+ let ids = null;
175
+ if (options.tag) {
176
+ const rows = await findMany(ARTICLE_TAGS, {
177
+ where: [{ field: 'tag', operator: '=', value: options.tag }],
178
+ select: ['articleId'],
179
+ });
180
+ ids = rows.map((r) => r.articleId);
181
+ }
182
+ if (options.favoritedBy) {
183
+ const rows = await findMany(REACTIONS, {
184
+ where: [
185
+ { field: 'resourceType', operator: '=', value: ARTICLE_RESOURCE_TYPE },
186
+ { field: 'type', operator: '=', value: FAVORITE_REACTION },
187
+ { field: 'userId', operator: '=', value: options.favoritedBy },
188
+ ],
189
+ select: ['resourceId'],
190
+ });
191
+ const favorited = new Set(rows.map((r) => r.resourceId));
192
+ ids = (ids ?? [...favorited]).filter((id) => favorited.has(id));
193
+ }
194
+ return ids;
195
+ }
196
+ /**
197
+ * Articles newest first, filtered by tag, author and who favorited them.
198
+ *
199
+ * @param options - Filters, paging and the viewer.
200
+ * @returns A page of articles and the total matching.
201
+ */
202
+ export async function listArticles(options = {}) {
203
+ const { limit, offset } = pageOf(options);
204
+ const ids = await filteredIds(options);
205
+ if (ids !== null && ids.length === 0)
206
+ return { data: [], total: 0, limit, offset };
207
+ const where = [
208
+ ...(options.authorId
209
+ ? [{ field: 'authorId', operator: '=', value: options.authorId }]
210
+ : []),
211
+ ...(ids !== null ? [{ field: 'id', operator: 'in', value: ids }] : []),
212
+ ];
213
+ const [rows, total] = await Promise.all([
214
+ findMany(ARTICLES, {
215
+ where,
216
+ orderBy: [{ field: 'createdAt', direction: 'desc' }],
217
+ limit,
218
+ offset,
219
+ }),
220
+ count(ARTICLES, where),
221
+ ]);
222
+ return { data: await hydrateArticles(rows, options.viewerId), total, limit, offset };
223
+ }
224
+ /**
225
+ * Articles by the users `userId` follows, newest first.
226
+ *
227
+ * @param userId - The reader.
228
+ * @param options - Paging.
229
+ * @returns A page of articles and the total.
230
+ */
231
+ export async function getFeed(userId, options = {}) {
232
+ const { limit, offset } = pageOf(options);
233
+ const follows = await findMany(FOLLOWS, {
234
+ where: [
235
+ { field: 'followerId', operator: '=', value: userId },
236
+ { field: 'targetType', operator: '=', value: 'user' },
237
+ ],
238
+ select: ['targetId'],
239
+ });
240
+ const authors = follows.map((f) => f.targetId);
241
+ if (authors.length === 0)
242
+ return { data: [], total: 0, limit, offset };
243
+ const where = [{ field: 'authorId', operator: 'in', value: authors }];
244
+ const [rows, total] = await Promise.all([
245
+ findMany(ARTICLES, {
246
+ where,
247
+ orderBy: [{ field: 'createdAt', direction: 'desc' }],
248
+ limit,
249
+ offset,
250
+ }),
251
+ count(ARTICLES, where),
252
+ ]);
253
+ return { data: await hydrateArticles(rows, userId), total, limit, offset };
254
+ }
255
+ /**
256
+ * Update an article. Only its author may; a changed title gives it a new slug.
257
+ *
258
+ * @param slug - The article slug.
259
+ * @param userId - The requesting user.
260
+ * @param input - The fields to change.
261
+ * @returns The updated article, or why not.
262
+ */
263
+ export async function updateArticle(slug, userId, input) {
264
+ const row = await findArticleRow(slug);
265
+ if (!row)
266
+ return { status: 'not_found' };
267
+ if (row.authorId !== userId)
268
+ return { status: 'forbidden' };
269
+ const patch = { updatedAt: new Date().toISOString() };
270
+ if (input.title !== undefined && input.title !== row.title) {
271
+ patch.title = input.title;
272
+ patch.slug = await articleSlug(input.title, row.id);
273
+ }
274
+ if (input.description !== undefined)
275
+ patch.description = input.description;
276
+ if (input.body !== undefined)
277
+ patch.body = input.body;
278
+ const tags = input.tagList !== undefined ? cleanTags(input.tagList) : null;
279
+ if (tags)
280
+ patch.tagList = JSON.stringify(tags);
281
+ const result = await updateById(ARTICLES, row.id, patch);
282
+ if (tags)
283
+ await writeTags(row.id, tags);
284
+ const updated = result.data ?? { ...row, ...patch };
285
+ const [article] = await hydrateArticles([updated], userId);
286
+ return { status: 'ok', article };
287
+ }
288
+ /**
289
+ * Delete an article and its tags and favorites. Only its author may.
290
+ *
291
+ * @param slug - The article slug.
292
+ * @param userId - The requesting user.
293
+ * @returns Whether it was deleted, or why not.
294
+ */
295
+ export async function deleteArticle(slug, userId) {
296
+ const row = await findArticleRow(slug);
297
+ if (!row)
298
+ return { status: 'not_found' };
299
+ if (row.authorId !== userId)
300
+ return { status: 'forbidden' };
301
+ await deleteMany(ARTICLE_TAGS, [{ field: 'articleId', operator: '=', value: row.id }]);
302
+ await deleteMany(REACTIONS, [
303
+ { field: 'resourceType', operator: '=', value: ARTICLE_RESOURCE_TYPE },
304
+ { field: 'resourceId', operator: '=', value: row.id },
305
+ ]);
306
+ await deleteById(ARTICLES, row.id);
307
+ return { status: 'ok', article: true };
308
+ }
309
+ /**
310
+ * Favorite or unfavorite an article for a user (idempotent both ways).
311
+ *
312
+ * @param slug - The article slug.
313
+ * @param userId - The user.
314
+ * @param favorite - True to favorite, false to remove the favorite.
315
+ * @returns The article after the change, or null when there is no such article.
316
+ */
317
+ export async function setFavorite(slug, userId, favorite) {
318
+ const row = await findArticleRow(slug);
319
+ if (!row)
320
+ return null;
321
+ if (favorite)
322
+ await addReaction(ARTICLE_RESOURCE_TYPE, row.id, userId, FAVORITE_REACTION);
323
+ else
324
+ await removeReaction(ARTICLE_RESOURCE_TYPE, row.id, userId, FAVORITE_REACTION);
325
+ const [article] = await hydrateArticles([row], userId);
326
+ return article;
327
+ }
328
+ /**
329
+ * Tags in use, most-used first.
330
+ *
331
+ * @param limit - How many to return (default 20).
332
+ * @returns Tags with their article counts.
333
+ */
334
+ export async function popularTags(limit = 20) {
335
+ const rows = await findMany(ARTICLE_TAGS, { select: ['tag'], limit: 50_000 });
336
+ const counts = new Map();
337
+ for (const r of rows)
338
+ counts.set(r.tag, (counts.get(r.tag) ?? 0) + 1);
339
+ return [...counts.entries()]
340
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
341
+ .slice(0, Math.max(1, limit))
342
+ .map(([tag, n]) => ({ tag, count: n }));
343
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Article resource type definitions.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * An article row as stored. `tagList` is a JSON array of tag names.
8
+ */
9
+ export interface ArticleRow {
10
+ /** Unique article identifier. */
11
+ id: string;
12
+ /** URL slug, unique across articles. */
13
+ slug: string;
14
+ /** Title. */
15
+ title: string;
16
+ /** Short summary shown in lists. */
17
+ description: string;
18
+ /** Full body (markdown or plain text — the app decides how to render it). */
19
+ body: string;
20
+ /** Tag names, JSON-encoded. */
21
+ tagList: string;
22
+ /** The user who wrote it. */
23
+ authorId: string;
24
+ /** When it was created (ISO 8601, millisecond precision). */
25
+ createdAt: string;
26
+ /** When it was last updated (ISO 8601). */
27
+ updatedAt: string;
28
+ }
29
+ /**
30
+ * An article as the service returns it: tags decoded, favorites counted, and
31
+ * whether the viewing user favorited it.
32
+ */
33
+ export interface Article {
34
+ /** Unique article identifier. */
35
+ id: string;
36
+ /** URL slug, unique across articles. */
37
+ slug: string;
38
+ /** Title. */
39
+ title: string;
40
+ /** Short summary shown in lists. */
41
+ description: string;
42
+ /** Full body. */
43
+ body: string;
44
+ /** Tag names, in the order they were given. */
45
+ tagList: string[];
46
+ /** The user who wrote it. */
47
+ authorId: string;
48
+ /** When it was created (ISO 8601). */
49
+ createdAt: string;
50
+ /** When it was last updated (ISO 8601). */
51
+ updatedAt: string;
52
+ /** How many users favorited it. */
53
+ favoritesCount: number;
54
+ /** Whether the viewing user favorited it (`false` with no viewer). */
55
+ favorited: boolean;
56
+ }
57
+ /**
58
+ * Input for creating an article.
59
+ */
60
+ export interface CreateArticleInput {
61
+ /** Title (the slug is derived from it). */
62
+ title: string;
63
+ /** Short summary. */
64
+ description?: string;
65
+ /** Full body. */
66
+ body: string;
67
+ /** Tag names. */
68
+ tagList?: string[];
69
+ }
70
+ /**
71
+ * Input for updating an article. A changed title gives the article a new slug.
72
+ */
73
+ export interface UpdateArticleInput {
74
+ /** New title. */
75
+ title?: string;
76
+ /** New summary. */
77
+ description?: string;
78
+ /** New body. */
79
+ body?: string;
80
+ /** New tag names (replaces the old ones). */
81
+ tagList?: string[];
82
+ }
83
+ /**
84
+ * Filters and paging for {@link listArticles}.
85
+ */
86
+ export interface ListArticlesOptions {
87
+ /** Only articles with this tag. */
88
+ tag?: string;
89
+ /** Only articles by this author id. */
90
+ authorId?: string;
91
+ /** Only articles this user id favorited. */
92
+ favoritedBy?: string;
93
+ /** Page size (default 20, at most 100). */
94
+ limit?: number;
95
+ /** Rows to skip. */
96
+ offset?: number;
97
+ /** The viewing user, for `favorited`. */
98
+ viewerId?: string;
99
+ }
100
+ /**
101
+ * A page of articles.
102
+ */
103
+ export interface PaginatedArticles {
104
+ /** The articles on this page, newest first. */
105
+ data: Article[];
106
+ /** Articles matching the filters across all pages. */
107
+ total: number;
108
+ /** Page size used. */
109
+ limit: number;
110
+ /** Rows skipped. */
111
+ offset: number;
112
+ }
113
+ /**
114
+ * A tag and how many articles carry it.
115
+ */
116
+ export interface TagCount {
117
+ /** Tag name. */
118
+ tag: string;
119
+ /** Articles with this tag. */
120
+ count: number;
121
+ }
122
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,iCAAiC;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa;IACb,KAAK,EAAE,MAAM,CAAA;IACb,oCAAoC;IACpC,WAAW,EAAE,MAAM,CAAA;IACnB,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAA;IACZ,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAA;IACf,6BAA6B;IAC7B,QAAQ,EAAE,MAAM,CAAA;IAChB,6DAA6D;IAC7D,SAAS,EAAE,MAAM,CAAA;IACjB,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAA;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,OAAO;IACtB,iCAAiC;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa;IACb,KAAK,EAAE,MAAM,CAAA;IACb,oCAAoC;IACpC,WAAW,EAAE,MAAM,CAAA;IACnB,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ,+CAA+C;IAC/C,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,6BAA6B;IAC7B,QAAQ,EAAE,MAAM,CAAA;IAChB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAA;IACjB,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAA;IACjB,mCAAmC;IACnC,cAAc,EAAE,MAAM,CAAA;IACtB,sEAAsE;IACtE,SAAS,EAAE,OAAO,CAAA;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAA;IACb,qBAAqB;IACrB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAA;IACZ,iBAAiB;IACjB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,iBAAiB;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,mBAAmB;IACnB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gBAAgB;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,mCAAmC;IACnC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,4CAA4C;IAC5C,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,2CAA2C;IAC3C,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,oBAAoB;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,yCAAyC;IACzC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,+CAA+C;IAC/C,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,sDAAsD;IACtD,KAAK,EAAE,MAAM,CAAA;IACb,sBAAsB;IACtB,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB;IACpB,MAAM,EAAE,MAAM,CAAA;CACf;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,gBAAgB;IAChB,GAAG,EAAE,MAAM,CAAA;IACX,8BAA8B;IAC9B,KAAK,EAAE,MAAM,CAAA;CACd"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Article resource type definitions.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Article input validation schemas.
3
+ *
4
+ * @module
5
+ */
6
+ import { z } from 'zod';
7
+ /**
8
+ * Schema for creating an article.
9
+ */
10
+ export declare const createArticleSchema: z.ZodObject<{
11
+ title: z.ZodString;
12
+ description: z.ZodOptional<z.ZodString>;
13
+ body: z.ZodString;
14
+ tagList: z.ZodOptional<z.ZodArray<z.ZodString>>;
15
+ }, z.core.$strip>;
16
+ /**
17
+ * Schema for updating an article (every field optional).
18
+ */
19
+ export declare const updateArticleSchema: z.ZodObject<{
20
+ title: z.ZodOptional<z.ZodString>;
21
+ description: z.ZodOptional<z.ZodString>;
22
+ body: z.ZodOptional<z.ZodString>;
23
+ tagList: z.ZodOptional<z.ZodArray<z.ZodString>>;
24
+ }, z.core.$strip>;
25
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAKvB;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;iBAK9B,CAAA;AAEF;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;iBAK9B,CAAA"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Article input validation schemas.
3
+ *
4
+ * @module
5
+ */
6
+ import { z } from 'zod';
7
+ /** Tag names: trimmed, non-empty, at most 50 characters, at most 20 of them. */
8
+ const tagList = z.array(z.string().trim().min(1).max(50)).max(20);
9
+ /**
10
+ * Schema for creating an article.
11
+ */
12
+ export const createArticleSchema = z.object({
13
+ title: z.string().trim().min(1).max(300),
14
+ description: z.string().max(1_000).optional(),
15
+ body: z.string().min(1).max(200_000),
16
+ tagList: tagList.optional(),
17
+ });
18
+ /**
19
+ * Schema for updating an article (every field optional).
20
+ */
21
+ export const updateArticleSchema = z.object({
22
+ title: z.string().trim().min(1).max(300).optional(),
23
+ description: z.string().max(1_000).optional(),
24
+ body: z.string().min(1).max(200_000).optional(),
25
+ tagList: tagList.optional(),
26
+ });