@molecule/api-resource-article 0.0.0-stage → 1.0.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/LICENSE +202 -0
- package/README.md +647 -2
- package/dist/authorizers/index.d.ts +11 -0
- package/dist/authorizers/index.d.ts.map +1 -0
- package/dist/authorizers/index.js +10 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/handlers/index.d.ts +61 -0
- package/dist/handlers/index.d.ts.map +1 -0
- package/dist/handlers/index.js +175 -0
- package/dist/handlers/shared.d.ts +64 -0
- package/dist/handlers/shared.d.ts.map +1 -0
- package/dist/handlers/shared.js +87 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +83 -0
- package/dist/requestHandlerMap.d.ts +21 -0
- package/dist/requestHandlerMap.d.ts.map +1 -0
- package/dist/requestHandlerMap.js +20 -0
- package/dist/routes.d.ts +56 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +33 -0
- package/dist/service.d.ts +117 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +343 -0
- package/dist/types.d.ts +122 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/validation.d.ts +25 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +26 -0
- package/package.json +78 -4
- package/src/__setup__/articles.sql +24 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Article route handlers.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type { MoleculeRequest, MoleculeResponse } from '@molecule/api-resource';
|
|
7
|
+
/**
|
|
8
|
+
* `POST /articles` — create an article as the signed-in user.
|
|
9
|
+
*
|
|
10
|
+
* @param req - Body: `{ title, body, description?, tagList? }`.
|
|
11
|
+
* @param res - 201 with the article.
|
|
12
|
+
*/
|
|
13
|
+
export declare function create(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* `GET /articles` — newest first; `?tag=`, `?author=` (user id),
|
|
16
|
+
* `?favoritedBy=` (user id), `?limit=`, `?offset=`.
|
|
17
|
+
*
|
|
18
|
+
* @param req - The request.
|
|
19
|
+
* @param res - `{ data, total, limit, offset }`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function list(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* `GET /articles/feed` — articles by the authors the signed-in user follows.
|
|
24
|
+
*
|
|
25
|
+
* @param req - `?limit=`, `?offset=`.
|
|
26
|
+
* @param res - `{ data, total, limit, offset }`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function feed(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* `GET /articles/tags` — tags in use, most-used first (`?limit=`).
|
|
31
|
+
*
|
|
32
|
+
* @param req - The request.
|
|
33
|
+
* @param res - `[{ tag, count }]`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function tags(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* `GET /articles/:slug`.
|
|
38
|
+
*
|
|
39
|
+
* @param req - The request.
|
|
40
|
+
* @param res - The article, or 404.
|
|
41
|
+
*/
|
|
42
|
+
export declare function read(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* `PUT /articles/:slug` — author only; a new title gives a new slug.
|
|
45
|
+
*
|
|
46
|
+
* @param req - Body: any of `{ title, description, body, tagList }`.
|
|
47
|
+
* @param res - The updated article, 403 or 404.
|
|
48
|
+
*/
|
|
49
|
+
export declare function update(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* `DELETE /articles/:slug` — author only.
|
|
52
|
+
*
|
|
53
|
+
* @param req - The request.
|
|
54
|
+
* @param res - 204, 403 or 404.
|
|
55
|
+
*/
|
|
56
|
+
export declare function del(req: MoleculeRequest, res: MoleculeResponse): Promise<void>;
|
|
57
|
+
/** `POST /articles/:slug/favorite` — idempotent; returns the article. */
|
|
58
|
+
export declare const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
|
|
59
|
+
/** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
|
|
60
|
+
export declare const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<void>;
|
|
61
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/handlers/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAwB/E;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAWvF;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBrF;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAcrF;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAOrF;AAED;;;;;GAKG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CASrF;AAED;;;;;GAKG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAcvF;AAED;;;;;GAKG;AACH,wBAAsB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAYpF;AAiBD,yEAAyE;AACzE,eAAO,MAAM,QAAQ,QAdP,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,IAAI,CActB,CAAA;AAE7C,2EAA2E;AAC3E,eAAO,MAAM,UAAU,QAjBT,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,IAAI,CAiBnB,CAAA"}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Article route handlers.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { logger } from '@molecule/api-logger';
|
|
7
|
+
import { createArticle, deleteArticle, getArticleBySlug, getFeed, listArticles, popularTags, setFavorite, updateArticle, } from '../service.js';
|
|
8
|
+
import { createArticleSchema, updateArticleSchema } from '../validation.js';
|
|
9
|
+
import { failed, forbidden, invalid, notFound, queryInt, queryString, sessionUserId, unauthorized, } from './shared.js';
|
|
10
|
+
/**
|
|
11
|
+
* `POST /articles` — create an article as the signed-in user.
|
|
12
|
+
*
|
|
13
|
+
* @param req - Body: `{ title, body, description?, tagList? }`.
|
|
14
|
+
* @param res - 201 with the article.
|
|
15
|
+
*/
|
|
16
|
+
export async function create(req, res) {
|
|
17
|
+
const userId = sessionUserId(res);
|
|
18
|
+
if (!userId)
|
|
19
|
+
return unauthorized(res);
|
|
20
|
+
const parsed = createArticleSchema.safeParse(req.body);
|
|
21
|
+
if (!parsed.success)
|
|
22
|
+
return invalid(res, parsed.error.issues);
|
|
23
|
+
try {
|
|
24
|
+
res.status(201).json(await createArticle(userId, parsed.data));
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
logger.error('Failed to create article', { userId, error });
|
|
28
|
+
failed(res, 'article.error.createFailed', 'Failed to create article');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* `GET /articles` — newest first; `?tag=`, `?author=` (user id),
|
|
33
|
+
* `?favoritedBy=` (user id), `?limit=`, `?offset=`.
|
|
34
|
+
*
|
|
35
|
+
* @param req - The request.
|
|
36
|
+
* @param res - `{ data, total, limit, offset }`.
|
|
37
|
+
*/
|
|
38
|
+
export async function list(req, res) {
|
|
39
|
+
try {
|
|
40
|
+
res.json(await listArticles({
|
|
41
|
+
tag: queryString(req.query.tag),
|
|
42
|
+
authorId: queryString(req.query.author),
|
|
43
|
+
favoritedBy: queryString(req.query.favoritedBy),
|
|
44
|
+
limit: queryInt(req.query.limit),
|
|
45
|
+
offset: queryInt(req.query.offset),
|
|
46
|
+
viewerId: sessionUserId(res),
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
logger.error('Failed to list articles', { error });
|
|
51
|
+
failed(res, 'article.error.listFailed', 'Failed to list articles');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* `GET /articles/feed` — articles by the authors the signed-in user follows.
|
|
56
|
+
*
|
|
57
|
+
* @param req - `?limit=`, `?offset=`.
|
|
58
|
+
* @param res - `{ data, total, limit, offset }`.
|
|
59
|
+
*/
|
|
60
|
+
export async function feed(req, res) {
|
|
61
|
+
const userId = sessionUserId(res);
|
|
62
|
+
if (!userId)
|
|
63
|
+
return unauthorized(res);
|
|
64
|
+
try {
|
|
65
|
+
res.json(await getFeed(userId, {
|
|
66
|
+
limit: queryInt(req.query.limit),
|
|
67
|
+
offset: queryInt(req.query.offset),
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
logger.error('Failed to read the article feed', { userId, error });
|
|
72
|
+
failed(res, 'article.error.feedFailed', 'Failed to load the feed');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* `GET /articles/tags` — tags in use, most-used first (`?limit=`).
|
|
77
|
+
*
|
|
78
|
+
* @param req - The request.
|
|
79
|
+
* @param res - `[{ tag, count }]`.
|
|
80
|
+
*/
|
|
81
|
+
export async function tags(req, res) {
|
|
82
|
+
try {
|
|
83
|
+
res.json(await popularTags(queryInt(req.query.limit)));
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
logger.error('Failed to list article tags', { error });
|
|
87
|
+
failed(res, 'article.error.tagsFailed', 'Failed to list tags');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* `GET /articles/:slug`.
|
|
92
|
+
*
|
|
93
|
+
* @param req - The request.
|
|
94
|
+
* @param res - The article, or 404.
|
|
95
|
+
*/
|
|
96
|
+
export async function read(req, res) {
|
|
97
|
+
try {
|
|
98
|
+
const article = await getArticleBySlug(String(req.params.slug), sessionUserId(res));
|
|
99
|
+
if (!article)
|
|
100
|
+
return notFound(res);
|
|
101
|
+
res.json(article);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
logger.error('Failed to read article', { slug: req.params.slug, error });
|
|
105
|
+
failed(res, 'article.error.readFailed', 'Failed to load the article');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* `PUT /articles/:slug` — author only; a new title gives a new slug.
|
|
110
|
+
*
|
|
111
|
+
* @param req - Body: any of `{ title, description, body, tagList }`.
|
|
112
|
+
* @param res - The updated article, 403 or 404.
|
|
113
|
+
*/
|
|
114
|
+
export async function update(req, res) {
|
|
115
|
+
const userId = sessionUserId(res);
|
|
116
|
+
if (!userId)
|
|
117
|
+
return unauthorized(res);
|
|
118
|
+
const parsed = updateArticleSchema.safeParse(req.body);
|
|
119
|
+
if (!parsed.success)
|
|
120
|
+
return invalid(res, parsed.error.issues);
|
|
121
|
+
try {
|
|
122
|
+
const result = await updateArticle(String(req.params.slug), userId, parsed.data);
|
|
123
|
+
if (result.status === 'not_found')
|
|
124
|
+
return notFound(res);
|
|
125
|
+
if (result.status === 'forbidden')
|
|
126
|
+
return forbidden(res);
|
|
127
|
+
res.json(result.article);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
logger.error('Failed to update article', { slug: req.params.slug, userId, error });
|
|
131
|
+
failed(res, 'article.error.updateFailed', 'Failed to update article');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* `DELETE /articles/:slug` — author only.
|
|
136
|
+
*
|
|
137
|
+
* @param req - The request.
|
|
138
|
+
* @param res - 204, 403 or 404.
|
|
139
|
+
*/
|
|
140
|
+
export async function del(req, res) {
|
|
141
|
+
const userId = sessionUserId(res);
|
|
142
|
+
if (!userId)
|
|
143
|
+
return unauthorized(res);
|
|
144
|
+
try {
|
|
145
|
+
const result = await deleteArticle(String(req.params.slug), userId);
|
|
146
|
+
if (result.status === 'not_found')
|
|
147
|
+
return notFound(res);
|
|
148
|
+
if (result.status === 'forbidden')
|
|
149
|
+
return forbidden(res);
|
|
150
|
+
res.status(204).end();
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
logger.error('Failed to delete article', { slug: req.params.slug, userId, error });
|
|
154
|
+
failed(res, 'article.error.deleteFailed', 'Failed to delete article');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const favoriteHandler = (on) => async (req, res) => {
|
|
158
|
+
const userId = sessionUserId(res);
|
|
159
|
+
if (!userId)
|
|
160
|
+
return unauthorized(res);
|
|
161
|
+
try {
|
|
162
|
+
const article = await setFavorite(String(req.params.slug), userId, on);
|
|
163
|
+
if (!article)
|
|
164
|
+
return notFound(res);
|
|
165
|
+
res.json(article);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
logger.error('Failed to change an article favorite', { slug: req.params.slug, userId, error });
|
|
169
|
+
failed(res, 'article.error.favoriteFailed', 'Failed to update the favorite');
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/** `POST /articles/:slug/favorite` — idempotent; returns the article. */
|
|
173
|
+
export const favorite = favoriteHandler(true);
|
|
174
|
+
/** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
|
|
175
|
+
export const unfavorite = favoriteHandler(false);
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pieces every article handler shares.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type { MoleculeResponse } from '@molecule/api-resource';
|
|
7
|
+
/**
|
|
8
|
+
* The signed-in user's id, if any.
|
|
9
|
+
*
|
|
10
|
+
* @param res - The response (the session is on `res.locals`).
|
|
11
|
+
* @returns The user id, or undefined.
|
|
12
|
+
*/
|
|
13
|
+
export declare const sessionUserId: (res: MoleculeResponse) => string | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* Answer 401.
|
|
16
|
+
*
|
|
17
|
+
* @param res - The response.
|
|
18
|
+
*/
|
|
19
|
+
export declare const unauthorized: (res: MoleculeResponse) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Answer 404 for a missing article.
|
|
22
|
+
*
|
|
23
|
+
* @param res - The response.
|
|
24
|
+
*/
|
|
25
|
+
export declare const notFound: (res: MoleculeResponse) => void;
|
|
26
|
+
/**
|
|
27
|
+
* Answer 403 for a change only the author may make.
|
|
28
|
+
*
|
|
29
|
+
* @param res - The response.
|
|
30
|
+
*/
|
|
31
|
+
export declare const forbidden: (res: MoleculeResponse) => void;
|
|
32
|
+
/**
|
|
33
|
+
* Answer 500 after logging.
|
|
34
|
+
*
|
|
35
|
+
* @param res - The response.
|
|
36
|
+
* @param key - The i18n key (`article.error.*`).
|
|
37
|
+
* @param fallback - The English message.
|
|
38
|
+
*/
|
|
39
|
+
export declare const failed: (res: MoleculeResponse, key: string, fallback: string) => void;
|
|
40
|
+
/**
|
|
41
|
+
* Answer 400 for input that failed validation.
|
|
42
|
+
*
|
|
43
|
+
* @param res - The response.
|
|
44
|
+
* @param issues - The schema's issues.
|
|
45
|
+
*/
|
|
46
|
+
export declare const invalid: (res: MoleculeResponse, issues: ReadonlyArray<{
|
|
47
|
+
path: PropertyKey[];
|
|
48
|
+
message: string;
|
|
49
|
+
}>) => void;
|
|
50
|
+
/**
|
|
51
|
+
* A query-string number, or undefined.
|
|
52
|
+
*
|
|
53
|
+
* @param value - The raw query value.
|
|
54
|
+
* @returns The integer, or undefined when absent or not a number.
|
|
55
|
+
*/
|
|
56
|
+
export declare const queryInt: (value: unknown) => number | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* A query-string string, or undefined.
|
|
59
|
+
*
|
|
60
|
+
* @param value - The raw query value.
|
|
61
|
+
* @returns The trimmed string, or undefined when absent or empty.
|
|
62
|
+
*/
|
|
63
|
+
export declare const queryString: (value: unknown) => string | undefined;
|
|
64
|
+
//# sourceMappingURL=shared.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/handlers/shared.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D;;;;;GAKG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,gBAAgB,KAAG,MAAM,GAAG,SACE,CAAA;AAEjE;;;;GAIG;AACH,eAAO,MAAM,YAAY,GAAI,KAAK,gBAAgB,KAAG,IAKpD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,gBAAgB,KAAG,IAKhD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAI,KAAK,gBAAgB,KAAG,IAOjD,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,gBAAgB,EAAE,KAAK,MAAM,EAAE,UAAU,MAAM,KAAG,IAE7E,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,OAAO,GAClB,KAAK,gBAAgB,EACrB,QAAQ,aAAa,CAAC;IAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,KAC9D,IAKF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SAGlD,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,OAAO,KAAG,MAAM,GAAG,SACgB,CAAA"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pieces every article handler shares.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { t } from '@molecule/api-i18n';
|
|
7
|
+
/**
|
|
8
|
+
* The signed-in user's id, if any.
|
|
9
|
+
*
|
|
10
|
+
* @param res - The response (the session is on `res.locals`).
|
|
11
|
+
* @returns The user id, or undefined.
|
|
12
|
+
*/
|
|
13
|
+
export const sessionUserId = (res) => res.locals.session?.userId;
|
|
14
|
+
/**
|
|
15
|
+
* Answer 401.
|
|
16
|
+
*
|
|
17
|
+
* @param res - The response.
|
|
18
|
+
*/
|
|
19
|
+
export const unauthorized = (res) => {
|
|
20
|
+
res.status(401).json({
|
|
21
|
+
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
22
|
+
errorKey: 'resource.error.unauthorized',
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Answer 404 for a missing article.
|
|
27
|
+
*
|
|
28
|
+
* @param res - The response.
|
|
29
|
+
*/
|
|
30
|
+
export const notFound = (res) => {
|
|
31
|
+
res.status(404).json({
|
|
32
|
+
error: t('article.error.notFound', undefined, { defaultValue: 'Article not found' }),
|
|
33
|
+
errorKey: 'article.error.notFound',
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Answer 403 for a change only the author may make.
|
|
38
|
+
*
|
|
39
|
+
* @param res - The response.
|
|
40
|
+
*/
|
|
41
|
+
export const forbidden = (res) => {
|
|
42
|
+
res.status(403).json({
|
|
43
|
+
error: t('article.error.notAuthor', undefined, {
|
|
44
|
+
defaultValue: 'Only the author can change this article',
|
|
45
|
+
}),
|
|
46
|
+
errorKey: 'article.error.notAuthor',
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Answer 500 after logging.
|
|
51
|
+
*
|
|
52
|
+
* @param res - The response.
|
|
53
|
+
* @param key - The i18n key (`article.error.*`).
|
|
54
|
+
* @param fallback - The English message.
|
|
55
|
+
*/
|
|
56
|
+
export const failed = (res, key, fallback) => {
|
|
57
|
+
res.status(500).json({ error: t(key, undefined, { defaultValue: fallback }), errorKey: key });
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Answer 400 for input that failed validation.
|
|
61
|
+
*
|
|
62
|
+
* @param res - The response.
|
|
63
|
+
* @param issues - The schema's issues.
|
|
64
|
+
*/
|
|
65
|
+
export const invalid = (res, issues) => {
|
|
66
|
+
res.status(400).json({
|
|
67
|
+
error: issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', '),
|
|
68
|
+
errorKey: 'article.error.validationFailed',
|
|
69
|
+
});
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* A query-string number, or undefined.
|
|
73
|
+
*
|
|
74
|
+
* @param value - The raw query value.
|
|
75
|
+
* @returns The integer, or undefined when absent or not a number.
|
|
76
|
+
*/
|
|
77
|
+
export const queryInt = (value) => {
|
|
78
|
+
const n = parseInt(String(value ?? ''), 10);
|
|
79
|
+
return Number.isFinite(n) ? n : undefined;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* A query-string string, or undefined.
|
|
83
|
+
*
|
|
84
|
+
* @param value - The raw query value.
|
|
85
|
+
* @returns The trimmed string, or undefined when absent or empty.
|
|
86
|
+
*/
|
|
87
|
+
export const queryString = (value) => typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Articles and blog posts for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Articles with unique slugs, tags, favorites, a feed of the authors a user
|
|
5
|
+
* follows, and lists filtered by tag, author and who favorited them — the
|
|
6
|
+
* domain of a blog, a Medium-style platform (RealWorld "Conduit"), a news or
|
|
7
|
+
* docs site. Favorites are `@molecule/api-resource-reaction` reactions and the
|
|
8
|
+
* feed reads `@molecule/api-resource-follow`'s follows, so they are the same
|
|
9
|
+
* favorites and follows the rest of the app sees.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { routes, requestHandlerMap } from '@molecule/api-resource-article'
|
|
15
|
+
*
|
|
16
|
+
* // Wire routes into your Express app via mlcl inject:
|
|
17
|
+
* // POST /articles create (signed in)
|
|
18
|
+
* // GET /articles ?tag= &author= &favoritedBy= &limit= &offset=
|
|
19
|
+
* // GET /articles/feed authors the signed-in user follows
|
|
20
|
+
* // GET /articles/tags tags in use, most-used first
|
|
21
|
+
* // GET /articles/:slug
|
|
22
|
+
* // PUT /articles/:slug author only; a new title gives a new slug
|
|
23
|
+
* // DELETE /articles/:slug author only
|
|
24
|
+
* // POST /articles/:slug/favorite idempotent
|
|
25
|
+
* // DELETE /articles/:slug/favorite idempotent
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // An API with its own response shape (a spec you must match) uses the
|
|
31
|
+
* // service and writes its own envelope:
|
|
32
|
+
* import { createArticle, listArticles } from '@molecule/api-resource-article'
|
|
33
|
+
*
|
|
34
|
+
* router.post('/api/articles', authenticate, async (req, res) => {
|
|
35
|
+
* const article = await createArticle(userId, req.body.article)
|
|
36
|
+
* res.status(201).json({ article: { ...article, author: await profileOf(article.authorId) } })
|
|
37
|
+
* })
|
|
38
|
+
*
|
|
39
|
+
* const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
|
|
40
|
+
* // page.data[0].favorited, page.data[0].favoritesCount, page.total
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* - **Migration required.** `src/__setup__/articles.sql` creates `articles` and
|
|
45
|
+
* `article_tags`; the reaction and follow packages bring `reactions` and
|
|
46
|
+
* `follows`. Scaffolded apps apply all of them on boot.
|
|
47
|
+
* - **Lists are newest first and paginated** — `{ data, total, limit, offset }`,
|
|
48
|
+
* at most 100 per page. `createdAt` is written with milliseconds, so two
|
|
49
|
+
* articles from the same second still come back in order on SQLite.
|
|
50
|
+
* - **Slugs are unique and stable.** The first "Hello World" is `hello-world`,
|
|
51
|
+
* the next `hello-world-2`; `feed` and `tags` are never used (they are routes).
|
|
52
|
+
* Changing the title changes the slug — link with the slug the response returns.
|
|
53
|
+
* - **The author is the session user**, always: create ignores any client
|
|
54
|
+
* author, and update/delete answer 403 to anyone else.
|
|
55
|
+
* - **Reads are public**; `favorited` is `false` without a signed-in viewer.
|
|
56
|
+
* - Article bodies are stored as given. Render markdown with
|
|
57
|
+
* `@molecule/app-markdown` + a provider (sanitized HTML) on the client.
|
|
58
|
+
* - Comments on articles: `@molecule/api-resource-comment` with resource type
|
|
59
|
+
* `'article'` and the article id.
|
|
60
|
+
*
|
|
61
|
+
* @e2e
|
|
62
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
63
|
+
* each item to this app's actual screens/flows, and check every box off one
|
|
64
|
+
* by one. A box you can't check is an integration bug to fix — not a skip:
|
|
65
|
+
* - [ ] Publishing an article opens its page at the slug the API returned,
|
|
66
|
+
* and it shows first in the global list.
|
|
67
|
+
* - [ ] Two articles with the same title get different slugs and both open.
|
|
68
|
+
* - [ ] Filtering by a tag shows only articles with that tag.
|
|
69
|
+
* - [ ] Favoriting increments the count, survives a reload, and unfavoriting
|
|
70
|
+
* brings it back; a signed-out visitor sees the count but no "favorited".
|
|
71
|
+
* - [ ] The feed shows only articles by followed authors, and an empty feed
|
|
72
|
+
* shows a readable empty state.
|
|
73
|
+
* - [ ] Only the author sees edit/delete; another user's direct attempt is refused.
|
|
74
|
+
* - [ ] Deleting removes the article from every list after reload.
|
|
75
|
+
*/
|
|
76
|
+
export * from './authorizers/index.js';
|
|
77
|
+
export * from './browser-guard.js';
|
|
78
|
+
export * from './handlers/index.js';
|
|
79
|
+
export * from './requestHandlerMap.js';
|
|
80
|
+
export * from './routes.js';
|
|
81
|
+
export * from './service.js';
|
|
82
|
+
export * from './types.js';
|
|
83
|
+
export * from './validation.js';
|
|
84
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AAEH,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA;AACnC,cAAc,wBAAwB,CAAA;AACtC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Articles and blog posts for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Articles with unique slugs, tags, favorites, a feed of the authors a user
|
|
5
|
+
* follows, and lists filtered by tag, author and who favorited them — the
|
|
6
|
+
* domain of a blog, a Medium-style platform (RealWorld "Conduit"), a news or
|
|
7
|
+
* docs site. Favorites are `@molecule/api-resource-reaction` reactions and the
|
|
8
|
+
* feed reads `@molecule/api-resource-follow`'s follows, so they are the same
|
|
9
|
+
* favorites and follows the rest of the app sees.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { routes, requestHandlerMap } from '@molecule/api-resource-article'
|
|
15
|
+
*
|
|
16
|
+
* // Wire routes into your Express app via mlcl inject:
|
|
17
|
+
* // POST /articles create (signed in)
|
|
18
|
+
* // GET /articles ?tag= &author= &favoritedBy= &limit= &offset=
|
|
19
|
+
* // GET /articles/feed authors the signed-in user follows
|
|
20
|
+
* // GET /articles/tags tags in use, most-used first
|
|
21
|
+
* // GET /articles/:slug
|
|
22
|
+
* // PUT /articles/:slug author only; a new title gives a new slug
|
|
23
|
+
* // DELETE /articles/:slug author only
|
|
24
|
+
* // POST /articles/:slug/favorite idempotent
|
|
25
|
+
* // DELETE /articles/:slug/favorite idempotent
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // An API with its own response shape (a spec you must match) uses the
|
|
31
|
+
* // service and writes its own envelope:
|
|
32
|
+
* import { createArticle, listArticles } from '@molecule/api-resource-article'
|
|
33
|
+
*
|
|
34
|
+
* router.post('/api/articles', authenticate, async (req, res) => {
|
|
35
|
+
* const article = await createArticle(userId, req.body.article)
|
|
36
|
+
* res.status(201).json({ article: { ...article, author: await profileOf(article.authorId) } })
|
|
37
|
+
* })
|
|
38
|
+
*
|
|
39
|
+
* const page = await listArticles({ tag: 'dragons', limit: 20, offset: 0, viewerId })
|
|
40
|
+
* // page.data[0].favorited, page.data[0].favoritesCount, page.total
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* @remarks
|
|
44
|
+
* - **Migration required.** `src/__setup__/articles.sql` creates `articles` and
|
|
45
|
+
* `article_tags`; the reaction and follow packages bring `reactions` and
|
|
46
|
+
* `follows`. Scaffolded apps apply all of them on boot.
|
|
47
|
+
* - **Lists are newest first and paginated** — `{ data, total, limit, offset }`,
|
|
48
|
+
* at most 100 per page. `createdAt` is written with milliseconds, so two
|
|
49
|
+
* articles from the same second still come back in order on SQLite.
|
|
50
|
+
* - **Slugs are unique and stable.** The first "Hello World" is `hello-world`,
|
|
51
|
+
* the next `hello-world-2`; `feed` and `tags` are never used (they are routes).
|
|
52
|
+
* Changing the title changes the slug — link with the slug the response returns.
|
|
53
|
+
* - **The author is the session user**, always: create ignores any client
|
|
54
|
+
* author, and update/delete answer 403 to anyone else.
|
|
55
|
+
* - **Reads are public**; `favorited` is `false` without a signed-in viewer.
|
|
56
|
+
* - Article bodies are stored as given. Render markdown with
|
|
57
|
+
* `@molecule/app-markdown` + a provider (sanitized HTML) on the client.
|
|
58
|
+
* - Comments on articles: `@molecule/api-resource-comment` with resource type
|
|
59
|
+
* `'article'` and the article id.
|
|
60
|
+
*
|
|
61
|
+
* @e2e
|
|
62
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
63
|
+
* each item to this app's actual screens/flows, and check every box off one
|
|
64
|
+
* by one. A box you can't check is an integration bug to fix — not a skip:
|
|
65
|
+
* - [ ] Publishing an article opens its page at the slug the API returned,
|
|
66
|
+
* and it shows first in the global list.
|
|
67
|
+
* - [ ] Two articles with the same title get different slugs and both open.
|
|
68
|
+
* - [ ] Filtering by a tag shows only articles with that tag.
|
|
69
|
+
* - [ ] Favoriting increments the count, survives a reload, and unfavoriting
|
|
70
|
+
* brings it back; a signed-out visitor sees the count but no "favorited".
|
|
71
|
+
* - [ ] The feed shows only articles by followed authors, and an empty feed
|
|
72
|
+
* shows a readable empty state.
|
|
73
|
+
* - [ ] Only the author sees edit/delete; another user's direct attempt is refused.
|
|
74
|
+
* - [ ] Deleting removes the article from every list after reload.
|
|
75
|
+
*/
|
|
76
|
+
export * from './authorizers/index.js';
|
|
77
|
+
export * from './browser-guard.js';
|
|
78
|
+
export * from './handlers/index.js';
|
|
79
|
+
export * from './requestHandlerMap.js';
|
|
80
|
+
export * from './routes.js';
|
|
81
|
+
export * from './service.js';
|
|
82
|
+
export * from './types.js';
|
|
83
|
+
export * from './validation.js';
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps route handler names to their implementations.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { create, del, feed, list, read, tags, update } from './handlers/index.js';
|
|
7
|
+
/**
|
|
8
|
+
* Handler map for article routes.
|
|
9
|
+
*/
|
|
10
|
+
export declare const requestHandlerMap: {
|
|
11
|
+
readonly create: typeof create;
|
|
12
|
+
readonly list: typeof list;
|
|
13
|
+
readonly feed: typeof feed;
|
|
14
|
+
readonly tags: typeof tags;
|
|
15
|
+
readonly read: typeof read;
|
|
16
|
+
readonly update: typeof update;
|
|
17
|
+
readonly del: typeof del;
|
|
18
|
+
readonly favorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
19
|
+
readonly unfavorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=requestHandlerMap.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,MAAM,EACN,GAAG,EAEH,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EAEJ,MAAM,EACP,MAAM,qBAAqB,CAAA;AAE5B;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;CAUpB,CAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps route handler names to their implementations.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { create, del, favorite, feed, list, read, tags, unfavorite, update, } from './handlers/index.js';
|
|
7
|
+
/**
|
|
8
|
+
* Handler map for article routes.
|
|
9
|
+
*/
|
|
10
|
+
export const requestHandlerMap = {
|
|
11
|
+
create,
|
|
12
|
+
list,
|
|
13
|
+
feed,
|
|
14
|
+
tags,
|
|
15
|
+
read,
|
|
16
|
+
update,
|
|
17
|
+
del,
|
|
18
|
+
favorite,
|
|
19
|
+
unfavorite,
|
|
20
|
+
};
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
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 declare const routes: readonly [{
|
|
14
|
+
readonly method: "post";
|
|
15
|
+
readonly path: "/articles";
|
|
16
|
+
readonly handler: "create";
|
|
17
|
+
readonly middlewares: readonly ["authenticate"];
|
|
18
|
+
}, {
|
|
19
|
+
readonly method: "get";
|
|
20
|
+
readonly path: "/articles";
|
|
21
|
+
readonly handler: "list";
|
|
22
|
+
}, {
|
|
23
|
+
readonly method: "get";
|
|
24
|
+
readonly path: "/articles/feed";
|
|
25
|
+
readonly handler: "feed";
|
|
26
|
+
readonly middlewares: readonly ["authenticate"];
|
|
27
|
+
}, {
|
|
28
|
+
readonly method: "get";
|
|
29
|
+
readonly path: "/articles/tags";
|
|
30
|
+
readonly handler: "tags";
|
|
31
|
+
}, {
|
|
32
|
+
readonly method: "get";
|
|
33
|
+
readonly path: "/articles/:slug";
|
|
34
|
+
readonly handler: "read";
|
|
35
|
+
}, {
|
|
36
|
+
readonly method: "put";
|
|
37
|
+
readonly path: "/articles/:slug";
|
|
38
|
+
readonly handler: "update";
|
|
39
|
+
readonly middlewares: readonly ["authenticate"];
|
|
40
|
+
}, {
|
|
41
|
+
readonly method: "delete";
|
|
42
|
+
readonly path: "/articles/:slug";
|
|
43
|
+
readonly handler: "del";
|
|
44
|
+
readonly middlewares: readonly ["authenticate"];
|
|
45
|
+
}, {
|
|
46
|
+
readonly method: "post";
|
|
47
|
+
readonly path: "/articles/:slug/favorite";
|
|
48
|
+
readonly handler: "favorite";
|
|
49
|
+
readonly middlewares: readonly ["authenticate"];
|
|
50
|
+
}, {
|
|
51
|
+
readonly method: "delete";
|
|
52
|
+
readonly path: "/articles/:slug/favorite";
|
|
53
|
+
readonly handler: "unfavorite";
|
|
54
|
+
readonly middlewares: readonly ["authenticate"];
|
|
55
|
+
}];
|
|
56
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;GAEG;AACH,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoBT,CAAA"}
|