@molecule/api-resource-article 1.1.6 → 1.2.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/README.md +130 -93
- package/dist/handlers/http.d.ts +41 -0
- package/dist/handlers/http.d.ts.map +1 -0
- package/dist/handlers/http.js +74 -0
- package/dist/handlers/index.d.ts +2 -59
- package/dist/handlers/index.d.ts.map +1 -1
- package/dist/handlers/index.js +2 -175
- package/dist/handlers/operations.d.ts +71 -0
- package/dist/handlers/operations.d.ts.map +1 -0
- package/dist/handlers/operations.js +195 -0
- package/dist/handlers/shared.d.ts +12 -12
- package/dist/handlers/shared.d.ts.map +1 -1
- package/dist/handlers/shared.js +29 -24
- package/dist/index.d.ts +43 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +43 -8
- package/dist/requestHandlerMap.d.ts +7 -8
- package/dist/requestHandlerMap.d.ts.map +1 -1
- package/package.json +4 -7
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured article operations, before HTTP wire-format adaptation.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type { MoleculeRequest, MoleculeResponse, Response } 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 - The response context containing the session.
|
|
12
|
+
* @returns The created article or a structured error response.
|
|
13
|
+
*/
|
|
14
|
+
export declare function create(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
15
|
+
/**
|
|
16
|
+
* `GET /articles` — newest first; `?tag=`, `?author=` (user id),
|
|
17
|
+
* `?favoritedBy=` (user id), `?limit=`, `?offset=`.
|
|
18
|
+
*
|
|
19
|
+
* @param req - The request.
|
|
20
|
+
* @param res - The response context containing the viewer.
|
|
21
|
+
* @returns A structured page or error response.
|
|
22
|
+
*/
|
|
23
|
+
export declare function list(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
24
|
+
/**
|
|
25
|
+
* `GET /articles/feed` — articles by the authors the signed-in user follows.
|
|
26
|
+
*
|
|
27
|
+
* @param req - `?limit=`, `?offset=`.
|
|
28
|
+
* @param res - The response context containing the viewer.
|
|
29
|
+
* @returns A structured page or error response.
|
|
30
|
+
*/
|
|
31
|
+
export declare function feed(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
32
|
+
/**
|
|
33
|
+
* `GET /articles/tags` — every tag in use, most-used first.
|
|
34
|
+
*
|
|
35
|
+
* With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
|
|
36
|
+
* asks for; `?limit=` narrows it to that many most-used tags.
|
|
37
|
+
*
|
|
38
|
+
* @param req - The request; `?limit=` caps the list.
|
|
39
|
+
* @param _res - The unused response context.
|
|
40
|
+
* @returns A structured tag list or error response.
|
|
41
|
+
*/
|
|
42
|
+
export declare function tags(req: MoleculeRequest, _res: MoleculeResponse): Promise<Response>;
|
|
43
|
+
/**
|
|
44
|
+
* `GET /articles/:slug`.
|
|
45
|
+
*
|
|
46
|
+
* @param req - The request.
|
|
47
|
+
* @param res - The response context containing the viewer.
|
|
48
|
+
* @returns A structured article or not-found/error response.
|
|
49
|
+
*/
|
|
50
|
+
export declare function read(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
51
|
+
/**
|
|
52
|
+
* `PUT /articles/:slug` — author only; a new title gives a new slug.
|
|
53
|
+
*
|
|
54
|
+
* @param req - Body: any of `{ title, description, body, tagList }`.
|
|
55
|
+
* @param res - The response context containing the session.
|
|
56
|
+
* @returns The updated article or a structured permission/not-found/error response.
|
|
57
|
+
*/
|
|
58
|
+
export declare function update(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
59
|
+
/**
|
|
60
|
+
* `DELETE /articles/:slug` — author only.
|
|
61
|
+
*
|
|
62
|
+
* @param req - The request.
|
|
63
|
+
* @param res - The response context containing the session.
|
|
64
|
+
* @returns A structured empty success or permission/not-found/error response.
|
|
65
|
+
*/
|
|
66
|
+
export declare function del(req: MoleculeRequest, res: MoleculeResponse): Promise<Response>;
|
|
67
|
+
/** `POST /articles/:slug/favorite` — idempotent; returns the article. */
|
|
68
|
+
export declare const favorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<Response>;
|
|
69
|
+
/** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
|
|
70
|
+
export declare const unfavorite: (req: MoleculeRequest, res: MoleculeResponse) => Promise<Response>;
|
|
71
|
+
//# sourceMappingURL=operations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../../src/handlers/operations.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAyBzF;;;;;;GAMG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW3F;AAED;;;;;;;GAOG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBzF;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAezF;AAED;;;;;;;;;GASG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAW1F;AAED;;;;;;GAMG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CASzF;AAED;;;;;;GAMG;AACH,wBAAsB,MAAM,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAc3F;AAED;;;;;;GAMG;AACH,wBAAsB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAYxF;AAiBD,yEAAyE;AACzE,eAAO,MAAM,QAAQ,QAdP,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAc1B,CAAA;AAE7C,2EAA2E;AAC3E,eAAO,MAAM,UAAU,QAjBT,eAAe,OAAO,gBAAgB,KAAG,OAAO,CAAC,QAAQ,CAiBvB,CAAA"}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured article operations, before HTTP wire-format adaptation.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { logger } from '@molecule/api-logger';
|
|
7
|
+
import { allTags, 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 - The response context containing the session.
|
|
15
|
+
* @returns The created article or a structured error response.
|
|
16
|
+
*/
|
|
17
|
+
export async function create(req, res) {
|
|
18
|
+
const userId = sessionUserId(res);
|
|
19
|
+
if (!userId)
|
|
20
|
+
return unauthorized();
|
|
21
|
+
const parsed = createArticleSchema.safeParse(req.body);
|
|
22
|
+
if (!parsed.success)
|
|
23
|
+
return invalid(parsed.error.issues);
|
|
24
|
+
try {
|
|
25
|
+
return { statusCode: 201, body: await createArticle(userId, parsed.data) };
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
logger.error('Failed to create article', { userId, error });
|
|
29
|
+
return failed('article.error.createFailed', 'Failed to create article');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* `GET /articles` — newest first; `?tag=`, `?author=` (user id),
|
|
34
|
+
* `?favoritedBy=` (user id), `?limit=`, `?offset=`.
|
|
35
|
+
*
|
|
36
|
+
* @param req - The request.
|
|
37
|
+
* @param res - The response context containing the viewer.
|
|
38
|
+
* @returns A structured page or error response.
|
|
39
|
+
*/
|
|
40
|
+
export async function list(req, res) {
|
|
41
|
+
try {
|
|
42
|
+
return {
|
|
43
|
+
statusCode: 200,
|
|
44
|
+
body: await listArticles({
|
|
45
|
+
tag: queryString(req.query.tag),
|
|
46
|
+
authorId: queryString(req.query.author),
|
|
47
|
+
favoritedBy: queryString(req.query.favoritedBy),
|
|
48
|
+
limit: queryInt(req.query.limit),
|
|
49
|
+
offset: queryInt(req.query.offset),
|
|
50
|
+
viewerId: sessionUserId(res),
|
|
51
|
+
}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
logger.error('Failed to list articles', { error });
|
|
56
|
+
return failed('article.error.listFailed', 'Failed to list articles');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* `GET /articles/feed` — articles by the authors the signed-in user follows.
|
|
61
|
+
*
|
|
62
|
+
* @param req - `?limit=`, `?offset=`.
|
|
63
|
+
* @param res - The response context containing the viewer.
|
|
64
|
+
* @returns A structured page or error response.
|
|
65
|
+
*/
|
|
66
|
+
export async function feed(req, res) {
|
|
67
|
+
const userId = sessionUserId(res);
|
|
68
|
+
if (!userId)
|
|
69
|
+
return unauthorized();
|
|
70
|
+
try {
|
|
71
|
+
return {
|
|
72
|
+
statusCode: 200,
|
|
73
|
+
body: await getFeed(userId, {
|
|
74
|
+
limit: queryInt(req.query.limit),
|
|
75
|
+
offset: queryInt(req.query.offset),
|
|
76
|
+
}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
logger.error('Failed to read the article feed', { userId, error });
|
|
81
|
+
return failed('article.error.feedFailed', 'Failed to load the feed');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* `GET /articles/tags` — every tag in use, most-used first.
|
|
86
|
+
*
|
|
87
|
+
* With no `?limit=` this is the whole list, the shape RealWorld's `GET /tags`
|
|
88
|
+
* asks for; `?limit=` narrows it to that many most-used tags.
|
|
89
|
+
*
|
|
90
|
+
* @param req - The request; `?limit=` caps the list.
|
|
91
|
+
* @param _res - The unused response context.
|
|
92
|
+
* @returns A structured tag list or error response.
|
|
93
|
+
*/
|
|
94
|
+
export async function tags(req, _res) {
|
|
95
|
+
try {
|
|
96
|
+
const limit = queryInt(req.query.limit);
|
|
97
|
+
return {
|
|
98
|
+
statusCode: 200,
|
|
99
|
+
body: limit === undefined ? await allTags() : await popularTags(limit),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
logger.error('Failed to list article tags', { error });
|
|
104
|
+
return failed('article.error.tagsFailed', 'Failed to list tags');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* `GET /articles/:slug`.
|
|
109
|
+
*
|
|
110
|
+
* @param req - The request.
|
|
111
|
+
* @param res - The response context containing the viewer.
|
|
112
|
+
* @returns A structured article or not-found/error response.
|
|
113
|
+
*/
|
|
114
|
+
export async function read(req, res) {
|
|
115
|
+
try {
|
|
116
|
+
const article = await getArticleBySlug(String(req.params.slug), sessionUserId(res));
|
|
117
|
+
if (!article)
|
|
118
|
+
return notFound();
|
|
119
|
+
return { statusCode: 200, body: article };
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
logger.error('Failed to read article', { slug: req.params.slug, error });
|
|
123
|
+
return failed('article.error.readFailed', 'Failed to load the article');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* `PUT /articles/:slug` — author only; a new title gives a new slug.
|
|
128
|
+
*
|
|
129
|
+
* @param req - Body: any of `{ title, description, body, tagList }`.
|
|
130
|
+
* @param res - The response context containing the session.
|
|
131
|
+
* @returns The updated article or a structured permission/not-found/error response.
|
|
132
|
+
*/
|
|
133
|
+
export async function update(req, res) {
|
|
134
|
+
const userId = sessionUserId(res);
|
|
135
|
+
if (!userId)
|
|
136
|
+
return unauthorized();
|
|
137
|
+
const parsed = updateArticleSchema.safeParse(req.body);
|
|
138
|
+
if (!parsed.success)
|
|
139
|
+
return invalid(parsed.error.issues);
|
|
140
|
+
try {
|
|
141
|
+
const result = await updateArticle(String(req.params.slug), userId, parsed.data);
|
|
142
|
+
if (result.status === 'not_found')
|
|
143
|
+
return notFound();
|
|
144
|
+
if (result.status === 'forbidden')
|
|
145
|
+
return forbidden();
|
|
146
|
+
return { statusCode: 200, body: result.article };
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
logger.error('Failed to update article', { slug: req.params.slug, userId, error });
|
|
150
|
+
return failed('article.error.updateFailed', 'Failed to update article');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* `DELETE /articles/:slug` — author only.
|
|
155
|
+
*
|
|
156
|
+
* @param req - The request.
|
|
157
|
+
* @param res - The response context containing the session.
|
|
158
|
+
* @returns A structured empty success or permission/not-found/error response.
|
|
159
|
+
*/
|
|
160
|
+
export async function del(req, res) {
|
|
161
|
+
const userId = sessionUserId(res);
|
|
162
|
+
if (!userId)
|
|
163
|
+
return unauthorized();
|
|
164
|
+
try {
|
|
165
|
+
const result = await deleteArticle(String(req.params.slug), userId);
|
|
166
|
+
if (result.status === 'not_found')
|
|
167
|
+
return notFound();
|
|
168
|
+
if (result.status === 'forbidden')
|
|
169
|
+
return forbidden();
|
|
170
|
+
return { statusCode: 204, body: undefined };
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
logger.error('Failed to delete article', { slug: req.params.slug, userId, error });
|
|
174
|
+
return failed('article.error.deleteFailed', 'Failed to delete article');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const favoriteHandler = (on) => async (req, res) => {
|
|
178
|
+
const userId = sessionUserId(res);
|
|
179
|
+
if (!userId)
|
|
180
|
+
return unauthorized();
|
|
181
|
+
try {
|
|
182
|
+
const article = await setFavorite(String(req.params.slug), userId, on);
|
|
183
|
+
if (!article)
|
|
184
|
+
return notFound();
|
|
185
|
+
return { statusCode: 200, body: article };
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
logger.error('Failed to change an article favorite', { slug: req.params.slug, userId, error });
|
|
189
|
+
return failed('article.error.favoriteFailed', 'Failed to update the favorite');
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
/** `POST /articles/:slug/favorite` — idempotent; returns the article. */
|
|
193
|
+
export const favorite = favoriteHandler(true);
|
|
194
|
+
/** `DELETE /articles/:slug/favorite` — idempotent; returns the article. */
|
|
195
|
+
export const unfavorite = favoriteHandler(false);
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import type { MoleculeResponse } from '@molecule/api-resource';
|
|
6
|
+
import type { MoleculeResponse, Response } from '@molecule/api-resource';
|
|
7
7
|
/**
|
|
8
8
|
* The signed-in user's id, if any.
|
|
9
9
|
*
|
|
@@ -14,39 +14,39 @@ export declare const sessionUserId: (res: MoleculeResponse) => string | undefine
|
|
|
14
14
|
/**
|
|
15
15
|
* Answer 401.
|
|
16
16
|
*
|
|
17
|
-
* @
|
|
17
|
+
* @returns The structured unauthorized response.
|
|
18
18
|
*/
|
|
19
|
-
export declare const unauthorized: (
|
|
19
|
+
export declare const unauthorized: () => Response;
|
|
20
20
|
/**
|
|
21
21
|
* Answer 404 for a missing article.
|
|
22
22
|
*
|
|
23
|
-
* @
|
|
23
|
+
* @returns The structured not-found response.
|
|
24
24
|
*/
|
|
25
|
-
export declare const notFound: (
|
|
25
|
+
export declare const notFound: () => Response;
|
|
26
26
|
/**
|
|
27
27
|
* Answer 403 for a change only the author may make.
|
|
28
28
|
*
|
|
29
|
-
* @
|
|
29
|
+
* @returns The structured forbidden response.
|
|
30
30
|
*/
|
|
31
|
-
export declare const forbidden: (
|
|
31
|
+
export declare const forbidden: () => Response;
|
|
32
32
|
/**
|
|
33
33
|
* Answer 500 after logging.
|
|
34
34
|
*
|
|
35
|
-
* @param res - The response.
|
|
36
35
|
* @param key - The i18n key (`article.error.*`).
|
|
37
36
|
* @param fallback - The English message.
|
|
37
|
+
* @returns The structured failure response.
|
|
38
38
|
*/
|
|
39
|
-
export declare const failed: (
|
|
39
|
+
export declare const failed: (key: string, fallback: string) => Response;
|
|
40
40
|
/**
|
|
41
41
|
* Answer 400 for input that failed validation.
|
|
42
42
|
*
|
|
43
|
-
* @param res - The response.
|
|
44
43
|
* @param issues - The schema's issues.
|
|
44
|
+
* @returns The structured validation response.
|
|
45
45
|
*/
|
|
46
|
-
export declare const invalid: (
|
|
46
|
+
export declare const invalid: (issues: ReadonlyArray<{
|
|
47
47
|
path: PropertyKey[];
|
|
48
48
|
message: string;
|
|
49
|
-
}>) =>
|
|
49
|
+
}>) => Response;
|
|
50
50
|
/**
|
|
51
51
|
* A query-string number, or undefined.
|
|
52
52
|
*
|
|
@@ -1 +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;
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/handlers/shared.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAExE;;;;;GAKG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,gBAAgB,KAAG,MAAM,GAAG,SACE,CAAA;AAEjE;;;;GAIG;AACH,eAAO,MAAM,YAAY,QAAO,QAM9B,CAAA;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,QAAO,QAM1B,CAAA;AAEF;;;;GAIG;AACH,eAAO,MAAM,SAAS,QAAO,QAQ3B,CAAA;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,GAAI,KAAK,MAAM,EAAE,UAAU,MAAM,KAAG,QAGrD,CAAA;AAEF;;;;;GAKG;AACH,eAAO,MAAM,OAAO,GAClB,QAAQ,aAAa,CAAC;IAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,KAC9D,QAMD,CAAA;AAEF;;;;;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"}
|
package/dist/handlers/shared.js
CHANGED
|
@@ -14,60 +14,65 @@ export const sessionUserId = (res) => res.locals.session?.userId;
|
|
|
14
14
|
/**
|
|
15
15
|
* Answer 401.
|
|
16
16
|
*
|
|
17
|
-
* @
|
|
17
|
+
* @returns The structured unauthorized response.
|
|
18
18
|
*/
|
|
19
|
-
export const unauthorized = (
|
|
20
|
-
|
|
19
|
+
export const unauthorized = () => ({
|
|
20
|
+
statusCode: 401,
|
|
21
|
+
body: {
|
|
21
22
|
error: t('resource.error.unauthorized', undefined, { defaultValue: 'Unauthorized' }),
|
|
22
23
|
errorKey: 'resource.error.unauthorized',
|
|
23
|
-
}
|
|
24
|
-
};
|
|
24
|
+
},
|
|
25
|
+
});
|
|
25
26
|
/**
|
|
26
27
|
* Answer 404 for a missing article.
|
|
27
28
|
*
|
|
28
|
-
* @
|
|
29
|
+
* @returns The structured not-found response.
|
|
29
30
|
*/
|
|
30
|
-
export const notFound = (
|
|
31
|
-
|
|
31
|
+
export const notFound = () => ({
|
|
32
|
+
statusCode: 404,
|
|
33
|
+
body: {
|
|
32
34
|
error: t('article.error.notFound', undefined, { defaultValue: 'Article not found' }),
|
|
33
35
|
errorKey: 'article.error.notFound',
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
+
},
|
|
37
|
+
});
|
|
36
38
|
/**
|
|
37
39
|
* Answer 403 for a change only the author may make.
|
|
38
40
|
*
|
|
39
|
-
* @
|
|
41
|
+
* @returns The structured forbidden response.
|
|
40
42
|
*/
|
|
41
|
-
export const forbidden = (
|
|
42
|
-
|
|
43
|
+
export const forbidden = () => ({
|
|
44
|
+
statusCode: 403,
|
|
45
|
+
body: {
|
|
43
46
|
error: t('article.error.notAuthor', undefined, {
|
|
44
47
|
defaultValue: 'Only the author can change this article',
|
|
45
48
|
}),
|
|
46
49
|
errorKey: 'article.error.notAuthor',
|
|
47
|
-
}
|
|
48
|
-
};
|
|
50
|
+
},
|
|
51
|
+
});
|
|
49
52
|
/**
|
|
50
53
|
* Answer 500 after logging.
|
|
51
54
|
*
|
|
52
|
-
* @param res - The response.
|
|
53
55
|
* @param key - The i18n key (`article.error.*`).
|
|
54
56
|
* @param fallback - The English message.
|
|
57
|
+
* @returns The structured failure response.
|
|
55
58
|
*/
|
|
56
|
-
export const failed = (
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
+
export const failed = (key, fallback) => ({
|
|
60
|
+
statusCode: 500,
|
|
61
|
+
body: { error: t(key, undefined, { defaultValue: fallback }), errorKey: key },
|
|
62
|
+
});
|
|
59
63
|
/**
|
|
60
64
|
* Answer 400 for input that failed validation.
|
|
61
65
|
*
|
|
62
|
-
* @param res - The response.
|
|
63
66
|
* @param issues - The schema's issues.
|
|
67
|
+
* @returns The structured validation response.
|
|
64
68
|
*/
|
|
65
|
-
export const invalid = (
|
|
66
|
-
|
|
69
|
+
export const invalid = (issues) => ({
|
|
70
|
+
statusCode: 400,
|
|
71
|
+
body: {
|
|
67
72
|
error: issues.map((e) => `${e.path.map(String).join('.')}: ${e.message}`).join(', '),
|
|
68
73
|
errorKey: 'article.error.validationFailed',
|
|
69
|
-
}
|
|
70
|
-
};
|
|
74
|
+
},
|
|
75
|
+
});
|
|
71
76
|
/**
|
|
72
77
|
* A query-string number, or undefined.
|
|
73
78
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,31 @@
|
|
|
13
13
|
* unique, and `article_tags.position` is the order the tags were given in). It also ships
|
|
14
14
|
* `src/__setup__/reactions.sql` and `src/__setup__/follows.sql`, which create the `reactions` and `follows` tables it reads by name.
|
|
15
15
|
*
|
|
16
|
+
* **HTTP format is configuration.** In the scaffold's `App/Resource/Article/index.ts`,
|
|
17
|
+
* export `requestHandlerMap = createArticleHandlers({ mapRequest, mapResponse })`.
|
|
18
|
+
* Keep `create`, `list`, `feed`, `read`, `update`, `del`, `favorite`, `unfavorite`
|
|
19
|
+
* and `tags` in the package.
|
|
20
|
+
* `mapRequest` can unwrap bodies and resolve query filters. Async `mapResponse`
|
|
21
|
+
* can batch-load author profiles, omit fields from list items, rename pagination
|
|
22
|
+
* keys, wrap results, or translate error statuses and bodies. It receives errors
|
|
23
|
+
* and empty deletes too. Set the authenticated user on `res.locals.session.userId`.
|
|
24
|
+
*
|
|
25
|
+
* ```typescript
|
|
26
|
+
* import { createArticleHandlers } from '@molecule/api-resource-article'
|
|
27
|
+
*
|
|
28
|
+
* export const requestHandlerMap = createArticleHandlers({
|
|
29
|
+
* mapRequest: (req) => ({ body: req.body?.entry }),
|
|
30
|
+
* mapResponse: (result) => result.statusCode >= 400 || result.statusCode === 204
|
|
31
|
+
* ? result
|
|
32
|
+
* : { ...result, body: { entry: result.body } },
|
|
33
|
+
* })
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* Use the resulting map's handlers on the app's routes. For distinct route projections,
|
|
37
|
+
* create separate maps with separate options. The static `requestHandlerMap` keeps the
|
|
38
|
+
* native flat-body/raw-article format. Use service functions for a different domain workflow.
|
|
39
|
+
* Read Quick Start for filter mapping and early responses.
|
|
40
|
+
*
|
|
16
41
|
* @module
|
|
17
42
|
* @example
|
|
18
43
|
* ```typescript
|
|
@@ -32,17 +57,27 @@
|
|
|
32
57
|
*
|
|
33
58
|
* @example
|
|
34
59
|
* ```typescript
|
|
35
|
-
* //
|
|
36
|
-
*
|
|
37
|
-
* import { createArticle, listArticles } from '@molecule/api-resource-article'
|
|
60
|
+
* // Configure a publishing API's envelopes without rewriting its operations:
|
|
61
|
+
* import { createArticleHandlers } from '@molecule/api-resource-article'
|
|
38
62
|
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
63
|
+
* const publishing = createArticleHandlers({
|
|
64
|
+
* mapRequest: (req) => ({ body: req.body?.entry }),
|
|
65
|
+
* mapResponse: async (result) => {
|
|
66
|
+
* // Preserve validation, authorization, missing rows and empty deletes.
|
|
67
|
+
* if (result.statusCode >= 400 || result.statusCode === 204) return result
|
|
68
|
+
* // The app owns its projection. A list can batch-load author profiles here.
|
|
69
|
+
* return { ...result, body: { entry: result.body } }
|
|
70
|
+
* },
|
|
42
71
|
* })
|
|
72
|
+
* router.post('/entries', publishing.create) // authenticated session remains required
|
|
73
|
+
* router.get('/entries/:slug', publishing.read)
|
|
43
74
|
*
|
|
44
|
-
*
|
|
45
|
-
* //
|
|
75
|
+
* // mapRequest can also resolve an external filter name to a user id in req.query.
|
|
76
|
+
* // If a lookup finds nothing, return { response: { statusCode, body } } with
|
|
77
|
+
* // this API's empty-page response before querying. Never drop the filter.
|
|
78
|
+
* // Keep extra domain validation in route middleware before these handlers.
|
|
79
|
+
* // For a different domain model or custom workflow, call createArticle/listArticles
|
|
80
|
+
* // from a local route instead. The default requestHandlerMap never adopts these mappings.
|
|
46
81
|
* ```
|
|
47
82
|
*
|
|
48
83
|
* @example
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyJG;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
CHANGED
|
@@ -13,6 +13,31 @@
|
|
|
13
13
|
* unique, and `article_tags.position` is the order the tags were given in). It also ships
|
|
14
14
|
* `src/__setup__/reactions.sql` and `src/__setup__/follows.sql`, which create the `reactions` and `follows` tables it reads by name.
|
|
15
15
|
*
|
|
16
|
+
* **HTTP format is configuration.** In the scaffold's `App/Resource/Article/index.ts`,
|
|
17
|
+
* export `requestHandlerMap = createArticleHandlers({ mapRequest, mapResponse })`.
|
|
18
|
+
* Keep `create`, `list`, `feed`, `read`, `update`, `del`, `favorite`, `unfavorite`
|
|
19
|
+
* and `tags` in the package.
|
|
20
|
+
* `mapRequest` can unwrap bodies and resolve query filters. Async `mapResponse`
|
|
21
|
+
* can batch-load author profiles, omit fields from list items, rename pagination
|
|
22
|
+
* keys, wrap results, or translate error statuses and bodies. It receives errors
|
|
23
|
+
* and empty deletes too. Set the authenticated user on `res.locals.session.userId`.
|
|
24
|
+
*
|
|
25
|
+
* ```typescript
|
|
26
|
+
* import { createArticleHandlers } from '@molecule/api-resource-article'
|
|
27
|
+
*
|
|
28
|
+
* export const requestHandlerMap = createArticleHandlers({
|
|
29
|
+
* mapRequest: (req) => ({ body: req.body?.entry }),
|
|
30
|
+
* mapResponse: (result) => result.statusCode >= 400 || result.statusCode === 204
|
|
31
|
+
* ? result
|
|
32
|
+
* : { ...result, body: { entry: result.body } },
|
|
33
|
+
* })
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* Use the resulting map's handlers on the app's routes. For distinct route projections,
|
|
37
|
+
* create separate maps with separate options. The static `requestHandlerMap` keeps the
|
|
38
|
+
* native flat-body/raw-article format. Use service functions for a different domain workflow.
|
|
39
|
+
* Read Quick Start for filter mapping and early responses.
|
|
40
|
+
*
|
|
16
41
|
* @module
|
|
17
42
|
* @example
|
|
18
43
|
* ```typescript
|
|
@@ -32,17 +57,27 @@
|
|
|
32
57
|
*
|
|
33
58
|
* @example
|
|
34
59
|
* ```typescript
|
|
35
|
-
* //
|
|
36
|
-
*
|
|
37
|
-
* import { createArticle, listArticles } from '@molecule/api-resource-article'
|
|
60
|
+
* // Configure a publishing API's envelopes without rewriting its operations:
|
|
61
|
+
* import { createArticleHandlers } from '@molecule/api-resource-article'
|
|
38
62
|
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
63
|
+
* const publishing = createArticleHandlers({
|
|
64
|
+
* mapRequest: (req) => ({ body: req.body?.entry }),
|
|
65
|
+
* mapResponse: async (result) => {
|
|
66
|
+
* // Preserve validation, authorization, missing rows and empty deletes.
|
|
67
|
+
* if (result.statusCode >= 400 || result.statusCode === 204) return result
|
|
68
|
+
* // The app owns its projection. A list can batch-load author profiles here.
|
|
69
|
+
* return { ...result, body: { entry: result.body } }
|
|
70
|
+
* },
|
|
42
71
|
* })
|
|
72
|
+
* router.post('/entries', publishing.create) // authenticated session remains required
|
|
73
|
+
* router.get('/entries/:slug', publishing.read)
|
|
43
74
|
*
|
|
44
|
-
*
|
|
45
|
-
* //
|
|
75
|
+
* // mapRequest can also resolve an external filter name to a user id in req.query.
|
|
76
|
+
* // If a lookup finds nothing, return { response: { statusCode, body } } with
|
|
77
|
+
* // this API's empty-page response before querying. Never drop the filter.
|
|
78
|
+
* // Keep extra domain validation in route middleware before these handlers.
|
|
79
|
+
* // For a different domain model or custom workflow, call createArticle/listArticles
|
|
80
|
+
* // from a local route instead. The default requestHandlerMap never adopts these mappings.
|
|
46
81
|
* ```
|
|
47
82
|
*
|
|
48
83
|
* @example
|
|
@@ -3,18 +3,17 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import { create, del, feed, list, read, tags, update } from './handlers/index.js';
|
|
7
6
|
/**
|
|
8
7
|
* Handler map for article routes.
|
|
9
8
|
*/
|
|
10
9
|
export declare const requestHandlerMap: {
|
|
11
|
-
readonly create:
|
|
12
|
-
readonly list:
|
|
13
|
-
readonly feed:
|
|
14
|
-
readonly tags:
|
|
15
|
-
readonly read:
|
|
16
|
-
readonly update:
|
|
17
|
-
readonly del:
|
|
10
|
+
readonly create: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
11
|
+
readonly list: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
12
|
+
readonly feed: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
13
|
+
readonly tags: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
14
|
+
readonly read: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
15
|
+
readonly update: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
16
|
+
readonly del: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
18
17
|
readonly favorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
19
18
|
readonly unfavorite: (req: import("@molecule/api-resource").MoleculeRequest, res: import("@molecule/api-resource").MoleculeResponse) => Promise<void>;
|
|
20
19
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;
|
|
1
|
+
{"version":3,"file":"requestHandlerMap.d.ts","sourceRoot":"","sources":["../src/requestHandlerMap.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAcH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;CAUpB,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/api-resource-article",
|
|
3
|
-
"version": "1.1
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "Articles and blog posts: unique slugs, tags, favorites, a followed-authors feed, and filtered, paginated lists",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -38,7 +38,9 @@
|
|
|
38
38
|
"@molecule/api-resource-follow": "1.0.11",
|
|
39
39
|
"@molecule/api-resource-reaction": "1.0.7",
|
|
40
40
|
"@molecule/api-slug": "1.0.3",
|
|
41
|
+
"@types/express": "5.0.6",
|
|
41
42
|
"@types/node": "26.6.5",
|
|
43
|
+
"express": "5.3.0",
|
|
42
44
|
"typescript": "6.0.3",
|
|
43
45
|
"vitest": "4.1.12",
|
|
44
46
|
"zod": "4.6.7"
|
|
@@ -47,17 +49,12 @@
|
|
|
47
49
|
"@molecule/api-database": "^1.0.1",
|
|
48
50
|
"@molecule/api-i18n": "^1.0.1",
|
|
49
51
|
"@molecule/api-logger": "^1.0.1",
|
|
50
|
-
"@molecule/api-resource": "^1.0
|
|
52
|
+
"@molecule/api-resource": "^1.1.0",
|
|
51
53
|
"@molecule/api-resource-follow": "^1.0.5",
|
|
52
54
|
"@molecule/api-resource-reaction": "^1.0.3",
|
|
53
55
|
"@molecule/api-slug": "^1.0.0",
|
|
54
56
|
"zod": "^4.0.0"
|
|
55
57
|
},
|
|
56
|
-
"peerDependenciesMeta": {
|
|
57
|
-
"@molecule/api-resource": {
|
|
58
|
-
"optional": true
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
58
|
"repository": {
|
|
62
59
|
"type": "git",
|
|
63
60
|
"url": "https://github.com/molecule-dev/molecule.git",
|