@ccw-api/api 0.3.0 → 0.3.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 ADDED
@@ -0,0 +1,324 @@
1
+ # @ccw-api/api
2
+
3
+ CCW(创作社区)前后端接口 SDK,整合 `sso.ccw.site` 与 `community-web.ccw.site`
4
+ 两大服务的常用 API,提供完整的 TypeScript 类型与开箱即用的分页封装。
5
+
6
+ - 包格式:**ESM + CJS + .d.ts 三产物**同时产出
7
+ - 类型:所有请求 / 响应字段**强类型**,后端 key 固定约束(如 `MongoDBId`、`CNameOssUrl`、`UUID`)
8
+ - 分页:统一返回 `PagesRes<T>`(含 `totalNum` / `totalPages` / `sortField` 等元信息)
9
+
10
+ ---
11
+
12
+ ## 安装
13
+
14
+ ```bash
15
+ npm install @ccw-api/api
16
+ # 或
17
+ pnpm add @ccw-api/api
18
+ # 或
19
+ yarn add @ccw-api/api
20
+ ```
21
+
22
+ > 唯一运行时依赖:`@ccw-api/axios`(内置鉴权 header 注入的 axios 封装)。
23
+ > `@ccw-api/api` 已将常用的 token 设置方法 **`setToken` 重新导出**,无需再单独依赖 axios 包。
24
+
25
+ ---
26
+
27
+ ## 快速开始
28
+
29
+ ### 1. 初始化 Token(前置条件)
30
+
31
+ ```ts
32
+ import { setToken } from "@ccw-api/api";
33
+
34
+ // 直接传入后端下发的 session token
35
+ setToken("abcdefgfoo");
36
+ ```
37
+
38
+ 所有 `@ccw-api/api` 的方法都会复用同一个 axios 单例,**调用 API 时无需再传入鉴权参数**。
39
+
40
+ ### 2. 调用方式
41
+
42
+ ```ts
43
+ import { sso, communityWeb } from "@ccw-api/api"; // ✅ 推荐:具名导入
44
+ // 或
45
+ import api from "@ccw-api/api"; // ✅ default 导入:api.sso / api.communityWeb
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 模块一:SSO(sso.ccw.site)
51
+
52
+ 账号认证相关,共 3 个 API:
53
+
54
+ ```ts
55
+ const { loginByPassword, logout, logoutBySession } = sso;
56
+
57
+ // 账号密码登录
58
+ await loginByPassword("student_number", "xxxxx", {
59
+ device: "WEB",
60
+ browser: "Chrome",
61
+ });
62
+
63
+ // 登出当前 session
64
+ await logout();
65
+
66
+ // 强制某个 session 下线用于登陆设备管理
67
+ await logoutBySession("64...session_oid");
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 模块二:Community-Web(community-web.ccw.site)
73
+
74
+ 覆盖作品 / 学生 / 星球 / 评论 / 通知 / 任务 / 表情 / 签到 / 云资产 / 学科专区 等业务领域,共 **68 个 API**。
75
+ 下面是常用场景示例。
76
+
77
+ ### 学生与作品
78
+
79
+ ```ts
80
+ // 拉取学生档案
81
+ const profile = await communityWeb.getStudentProfile(
82
+ "63c2807d669fa967f17f5559",
83
+ );
84
+ // ^? StudentOverview(包含头像、简介、统计字段等)
85
+
86
+ // 我的创作分
87
+ const score = await communityWeb.getCreatorScore();
88
+ console.log(score.rank); // "ORDINARY" | "HACKER" | "ADVANCED"
89
+
90
+ // 分页拉取某学生的作品列表(含 totalNum / totalPages)
91
+ const creations = await communityWeb.getCreationsByStudent(
92
+ "63c2807d669fa967f17f5559",
93
+ { page: 1, perPage: 12, sortField: "createdAt", sortType: "DESC" },
94
+ );
95
+ // creations: PagesRes<CreationSimple>
96
+ console.log(creations.totalNum, creations.data[0].title);
97
+ ```
98
+
99
+ ### 星球(HashTag)与作品关联
100
+
101
+ ```ts
102
+ // 查询某作品加入了哪些星球
103
+ const planets = await communityWeb.getPlanetsOfCreation(
104
+ "69929185f8d6142487fd4b2e",
105
+ );
106
+ // planets: HashTagCreationRelation[]
107
+ // planets[0].rank → "ORDINARY"(星球审核等级,与创作分 CreatorScore.rank 概念不同)
108
+
109
+ // 查询我加入某星球的作品分页(排除一个星球 + 过滤状态)
110
+ const mine = await communityWeb.getMyHashTagCreations(
111
+ "蔚蓝档案",
112
+ ["PUBLISHED"],
113
+ { page: 1, perPage: 8, sortField: "lastPassedAt", sortType: "DESC" },
114
+ );
115
+ ```
116
+
117
+ ### 通知(细化了 15 种 contentCategory)
118
+
119
+ ```ts
120
+ import type {
121
+ NotificationContent,
122
+ PostCommentContent,
123
+ FollowedContent,
124
+ } from "@ccw-api/api";
125
+
126
+ const page = await communityWeb.getNotificationPage("COMMENT_TO_ME", {
127
+ page: 1,
128
+ perPage: 20,
129
+ });
130
+ // page.data[].content 类型是 NotificationContent(判别联合)
131
+ // 用 contentCategory 做类型收窄:
132
+
133
+ for (const notif of page.data) {
134
+ switch (notif.contentCategory) {
135
+ case "POST_COMMENT": {
136
+ const c = notif.content as PostCommentContent;
137
+ console.log("评论者:", c.sender, "文章:", c.subject_outline);
138
+ break;
139
+ }
140
+ case "FOLLOWED": {
141
+ const c = notif.content as FollowedContent;
142
+ console.log("新粉丝:", c.sender, c.sender_id);
143
+ break;
144
+ }
145
+ case "CREATION_SHARE":
146
+ case "SESSION_CREATED":
147
+ case "COMMUNITY_ACTIVITY":
148
+ case "POST_VISIBILITY_CHANGED":
149
+ // ……共 15 种,可按 IDE 补全逐项处理
150
+ }
151
+ }
152
+
153
+ // 拉取所有分组的未读统计
154
+ const stats = await communityWeb.getNotificationStats();
155
+ // stats.creationInteraction stats.commentToMe stats.followMe ……
156
+ ```
157
+
158
+ ### 任务、表情、金币、签到
159
+
160
+ ```ts
161
+ // 我的任务列表
162
+ const tasks = await communityWeb.getMyTasks();
163
+
164
+ // 领取某个任务奖励
165
+ await communityWeb.acceptAward("61273ccf1730f4308e853f6a");
166
+
167
+ // 个人金币余额(充值 / 赠送 / 提现 三栏分离)
168
+ const coin = await communityWeb.getPersonalCurrencyAccount();
169
+ // coin: { internalCurrencyBalance, topUpCurrencyBalance, withdrawCurrencyBalance }
170
+
171
+ // 全部表情包 + 分页 + 分类
172
+ const [allEmoji, emojiPage, categories] = await Promise.all([
173
+ communityWeb.getAllEmojis(),
174
+ communityWeb.getEmojiPage("ENABLED", { page: 1, perPage: 50 }),
175
+ communityWeb.getEmojiCategoryList(),
176
+ ]);
177
+
178
+ // 签到
179
+ await communityWeb.insertCheckInRecord(); // 今日打卡
180
+ const history = await communityWeb.getCheckInRecords();
181
+ ```
182
+
183
+ ### 黑名单、封禁、禁言查询
184
+
185
+ ```ts
186
+ const STUDENT = "63c2807d669fa967f17f5559";
187
+
188
+ // 轻量:是否拉黑(只返回 NOT_BLOCKED / BLOCKING)
189
+ const s = await communityWeb.getStudentBlockStatus(STUDENT);
190
+
191
+ // 详细:完整的 BlockActionRecord(拉黑动作记录,oid / createdAt / fromEntityId)
192
+ const detail = await communityWeb.getStudentBlockRecordDetail(STUDENT);
193
+
194
+ // 封禁详情(带泛型,locked=false 时其他字段全为 null)
195
+ const locked = await communityWeb.getLockedUserDetail<true>(
196
+ "642c0e8a59230841adf62406",
197
+ );
198
+
199
+ // 禁言详情(studentNumber 是 244373873 这种数字字符串,null 表示未禁言)
200
+ const muted = await communityWeb.getMutedUserDetail("244373873");
201
+ ```
202
+
203
+ ### 通用工具型 API
204
+
205
+ ```ts
206
+ // 生成短链
207
+ await communityWeb.createShortUrl("https://ccw.site/detail/xxx");
208
+
209
+ // 生成邀请码(api/v1/short_code/encode)
210
+ await communityWeb.encodeShortCode("hello world", 1, 6);
211
+
212
+ // 服务器时间
213
+ await communityWeb.getTime();
214
+
215
+ // 埋点事件上报
216
+ await communityWeb.sendEvent("creation_detail_view_6880873d2211fa69e41c9d19");
217
+
218
+ // 广告横幅
219
+ await communityWeb.getLeafletsItemList(1001);
220
+
221
+ // 学科专区(分页 / 按频道)
222
+ await communityWeb.getSubjectAreaPage({ page: 1, perPage: 20 });
223
+ await communityWeb.getSubjectAreaPageByChannel("PRIMARY");
224
+ ```
225
+
226
+ ---
227
+
228
+ ## 类型系统
229
+
230
+ ### 原语类型(`types/api.d.ts`)
231
+
232
+ 可直接从包顶层作为 `type` 导入:
233
+
234
+ ```ts
235
+ import type {
236
+ MongoDBId, // 24 位 hex 字符串(ObjectId)
237
+ CNameOssUrl, // https://m.ccw.site/... 或 https://m.xiguacity.cn/... OSS URL
238
+ UUID, // `${string}-${string}-${string}-${string}-${string}` 类型体操
239
+ ApiResponse, // { code, msg, body: T } 后端统一响应壳(SDK 内部已拆)
240
+ } from "@ccw-api/api";
241
+ ```
242
+
243
+ ### 领域命名空间
244
+
245
+ 每个 `types/*.d.ts` 作为一个命名空间重新导出,**避免同名类型冲突**(典型如 `Student` vs `StudentOverview` vs `Account.Types.Student`):
246
+
247
+ ```ts
248
+ import type {
249
+ Api, // 原语类型(MongoDBId / CNameOssUrl / UUID / ApiResponse ...)
250
+ UserData, // Student / StudentOverview / CreatorScore / UserCard ...
251
+ Creation, // Creation / HashTag / HashTagCreationRank / CreationRelease ...
252
+ Comment, // Comment / CommentStatus ...
253
+ Notification, // Notification / NotificationSenderInfo / NotificationGroup ...
254
+ NotificationContent, // 15 种通知 content 判别联合
255
+ Pages, // PageArgs / PagesRes
256
+ Session, // StudentSession / SessionArea
257
+ Account, // AccountTypes
258
+ Approval, // ApprovalTag
259
+ } from "@ccw-api/api";
260
+
261
+ type Score = UserData.CreatorScore["rank"]; // "ORDINARY" | "HACKER" | "ADVANCED"
262
+ type PlanetRank = Creation.HashTagCreationRank; // "ORDINARY"
263
+ ```
264
+
265
+ ---
266
+
267
+ ## 分页约定
268
+
269
+ 所有分页 API 都遵循同一套形状(详见 `types/pages.d.ts` + `src/queryPages.ts`):
270
+
271
+ ```ts
272
+ import type { PageArgs, PagesRes } from "@ccw-api/api";
273
+
274
+ // 入参 Partial<PageArgs<SortField>>,默认 { page:1, perPage:20, sortType:"DESC" }
275
+ // 出参 PagesRes<T> 完整结构:
276
+ const p: PagesRes<Creation.Creation> = {
277
+ data: [], // 当前页数据
278
+ page: 1,
279
+ perPage: 20,
280
+ offset: 0,
281
+ totalNum: 1234, // 总条数 —— 之前版本被截断,目前 SDK 已完整透出
282
+ totalPages: 62, // 总页数
283
+ sortField: "createdAt",
284
+ sortType: "DESC",
285
+ };
286
+ ```
287
+
288
+ ---
289
+
290
+ ## 开发 & 发布
291
+
292
+ ```bash
293
+ # 三产物构建(node / esm / .d.ts)
294
+ npm run build
295
+
296
+ # 跑测试(Jest 30 + ts-jest,67 suites / 72 tests)
297
+ npm test
298
+ npm run test:dev # watch 模式
299
+
300
+ # 文档(TypeDoc,生成到 doc/ 或默认输出目录)
301
+ npm run doc
302
+ npm run doc:dev
303
+ ```
304
+
305
+ `npm publish` 会自动触发 `prepublishOnly` → **build + test** 全跑一遍,失败会阻断发布。
306
+
307
+ ---
308
+
309
+ ## 目录与规范
310
+
311
+ 所有 API 文件严格遵循 `AGENT.md` 规范:
312
+
313
+ - **按域名分组**:`src/sso` / `src/community-web`,内部子目录对应 URL 路径
314
+ - **单文件单接口**:文件名 `kebab-case`,对应 endpoint 最后一段
315
+ - **7 段式模板**(每个 API 文件内部固定顺序):
316
+ 1. `import`
317
+ 2. `export const url = "https://..."`(调试 & 测试直接引用)
318
+ 3. `export type Req = { ... }`
319
+ 4. `export type Res = { ... }`(响应体内部,不含 `ApiResponse` 外层)
320
+ 5. 辅助类型
321
+ 6. JSDoc(`@param` / `@returns`)
322
+ 7. `export async function xxx(): Promise<Res>`
323
+
324
+ 新增 API 时,**最后记得在 `src/community-web/index.ts` 里 `import + 对象字面量聚合导出`**,否则外部访问不到。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ccw-api/api",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "ccw api collections",
5
5
  "license": "MIT",
6
6
  "author": "Meng Fuzi",