hnch-core 0.1.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.
@@ -0,0 +1,92 @@
1
+ /**
2
+ * 底座统一响应 & 分页工具
3
+ *
4
+ * 用法:
5
+ * const { ok, created, notFound, paginate } = require('@hnch/core/response');
6
+ *
7
+ * res.json(ok(data));
8
+ * res.status(404).json(notFound('用户不存在'));
9
+ * res.json(paginate({ list, total, page, psize }));
10
+ */
11
+
12
+ // ── 成功响应 ──
13
+
14
+ function ok(data, message = 'success') {
15
+ return { success: true, code: 200, message, data };
16
+ }
17
+
18
+ function created(data, message = 'created') {
19
+ return { success: true, code: 201, message, data };
20
+ }
21
+
22
+ // ── 错误响应 ──
23
+
24
+ function fail(code, message, details) {
25
+ const body = { success: false, code, message };
26
+ if (details) body.details = details;
27
+ return body;
28
+ }
29
+
30
+ function badRequest(message = '请求参数错误', details) {
31
+ return fail(400, message, details);
32
+ }
33
+
34
+ function unauthorized(message = '未授权') {
35
+ return fail(401, message);
36
+ }
37
+
38
+ function forbidden(message = '无权限') {
39
+ return fail(403, message);
40
+ }
41
+
42
+ function notFound(message = '资源不存在') {
43
+ return fail(404, message);
44
+ }
45
+
46
+ function conflict(message = '数据冲突') {
47
+ return fail(409, message);
48
+ }
49
+
50
+ function internalError(message = '服务器内部错误') {
51
+ return fail(500, message);
52
+ }
53
+
54
+ // ── 分页 ──
55
+
56
+ /**
57
+ * 构建分页响应
58
+ *
59
+ * @param {Object} opts
60
+ * @param {Array} opts.list - 当前页数据
61
+ * @param {number} opts.total - 总条数
62
+ * @param {number} opts.page - 当前页码
63
+ * @param {number} opts.psize - 每页条数
64
+ */
65
+ function paginate({ list, total, page, psize }) {
66
+ return {
67
+ success: true,
68
+ data: list,
69
+ pagination: {
70
+ page: Number(page) || 1,
71
+ psize: Number(psize) || 20,
72
+ total: Number(total) || 0,
73
+ totalPages: psize ? Math.ceil(total / psize) : 0,
74
+ },
75
+ };
76
+ }
77
+
78
+ /**
79
+ * 从 req.query 提取分页参数
80
+ */
81
+ function pageParams(req, defaults = {}) {
82
+ return {
83
+ page: Math.max(1, parseInt(req.query.page) || defaults.page || 1),
84
+ psize: Math.min(100, Math.max(1, parseInt(req.query.psize) || defaults.psize || 20)),
85
+ };
86
+ }
87
+
88
+ module.exports = {
89
+ ok, created,
90
+ fail, badRequest, unauthorized, forbidden, notFound, conflict, internalError,
91
+ paginate, pageParams,
92
+ };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * SSO 服务客户端
3
+ *
4
+ * 统一的 SSO 服务间调用通道(SMS、邮件等)。
5
+ * 所有客户端平台共享此模块,避免重复的 fetch/JSON 解析/错误处理。
6
+ *
7
+ * 用法:
8
+ * const { createSSOClient } = require('@hnch/core/utils/sso-client');
9
+ * const sso = createSSOClient({
10
+ * ssoServer: process.env.SSO_SERVER || 'http://localhost:8000',
11
+ * apiKey: process.env.SERVICE_API_KEY || '',
12
+ * logger,
13
+ * });
14
+ *
15
+ * await sso.post('/api/service/sms/send/', { phone, ... });
16
+ * await sso.post('/api/service/email/send/', { to, subject, html });
17
+ */
18
+
19
+ function createSSOClient({ ssoServer, apiKey, logger }) {
20
+
21
+ /**
22
+ * 向 SSO 服务端发起 POST 请求
23
+ *
24
+ * @param {string} path - SSO 服务路径(以 / 开头,建议以 / 结尾)
25
+ * @param {object} body - 请求体
26
+ * @returns {Promise<object>} SSO 响应的 data 字段
27
+ */
28
+ async function post(path, body = {}) {
29
+ const res = await fetch(`${ssoServer}${path}`, {
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ 'Authorization': `Bearer ${apiKey}`,
34
+ },
35
+ body: JSON.stringify(body),
36
+ });
37
+
38
+ const text = await res.text();
39
+ let data;
40
+ try {
41
+ data = JSON.parse(text);
42
+ } catch {
43
+ if (logger) {
44
+ logger.error(`[SSO Client] 非 JSON 响应 (HTTP ${res.status}): ${text.slice(0, 200)}`);
45
+ }
46
+ throw new Error(`SSO 返回非预期响应 (HTTP ${res.status})`);
47
+ }
48
+
49
+ if (data.code !== 200) {
50
+ throw new Error(data.message || 'SSO 请求失败');
51
+ }
52
+
53
+ return data;
54
+ }
55
+
56
+ /**
57
+ * 带重试的 POST
58
+ */
59
+ async function postWithRetry(path, body, retries = 2, delay = 1000) {
60
+ for (let i = 0; i <= retries; i++) {
61
+ try {
62
+ return await post(path, body);
63
+ } catch (err) {
64
+ if (i === retries) throw err;
65
+ if (logger) {
66
+ logger.warn(`[SSO Client] 重试 ${i + 1}/${retries}: ${err.message}`);
67
+ }
68
+ await new Promise(r => setTimeout(r, delay));
69
+ }
70
+ }
71
+ }
72
+
73
+ return { post, postWithRetry };
74
+ }
75
+
76
+ module.exports = { createSSOClient };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 底座工具函数
3
+ *
4
+ * 用法:
5
+ * const { retry, timeout, hash, sleep } = require('@hnch/core/utils');
6
+ *
7
+ * const data = await retry(() => fetch(url), { times: 3, delay: 1000 });
8
+ * const data = await timeout(fetch(url), 5000);
9
+ */
10
+
11
+ const crypto = require('crypto');
12
+
13
+ /**
14
+ * 重试执行异步函数
15
+ *
16
+ * @param {Function} fn - 异步函数
17
+ * @param {Object} options
18
+ * @param {number} options.times - 最大重试次数 (默认 3)
19
+ * @param {number} options.delay - 重试间隔 ms (默认 1000)
20
+ * @param {Function} options.onRetry - 每次重试回调 (err, attempt) => void
21
+ */
22
+ async function retry(fn, options = {}) {
23
+ const { times = 3, delay = 1000, onRetry } = options;
24
+ let lastErr;
25
+
26
+ for (let i = 0; i <= times; i++) {
27
+ try {
28
+ return await fn();
29
+ } catch (err) {
30
+ lastErr = err;
31
+ if (i < times) {
32
+ if (onRetry) onRetry(err, i + 1);
33
+ await sleep(delay);
34
+ }
35
+ }
36
+ }
37
+ throw lastErr;
38
+ }
39
+
40
+ /**
41
+ * 带超时的异步执行
42
+ *
43
+ * @param {Promise|Function} promiseOrFn
44
+ * @param {number} ms - 超时毫秒
45
+ */
46
+ async function timeout(promiseOrFn, ms) {
47
+ const promise = typeof promiseOrFn === 'function' ? promiseOrFn() : promiseOrFn;
48
+ let timer;
49
+ const timeoutPromise = new Promise((_, reject) => {
50
+ timer = setTimeout(() => reject(new Error(`操作超时 (${ms}ms)`)), ms);
51
+ });
52
+ try {
53
+ return await Promise.race([promise, timeoutPromise]);
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ }
58
+
59
+ /** sleep (ms) */
60
+ function sleep(ms) {
61
+ return new Promise(resolve => setTimeout(resolve, ms));
62
+ }
63
+
64
+ /** SHA256 hash */
65
+ function sha256(str) {
66
+ return crypto.createHash('sha256').update(str).digest('hex');
67
+ }
68
+
69
+ /** MD5 hash */
70
+ function md5(str) {
71
+ return crypto.createHash('md5').update(str).digest('hex');
72
+ }
73
+
74
+ /** 随机字符串 */
75
+ function randomStr(length = 16) {
76
+ return crypto.randomBytes(length).toString('hex').slice(0, length);
77
+ }
78
+
79
+ /** 安全 JSON parse */
80
+ function safeJsonParse(str, fallback = null) {
81
+ try { return JSON.parse(str); } catch { return fallback; }
82
+ }
83
+
84
+ module.exports = {
85
+ retry, timeout, sleep,
86
+ sha256, md5, randomStr,
87
+ safeJsonParse,
88
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 底座校验工具
3
+ *
4
+ * 用法:
5
+ * const { validate, rules } = require('@hnch/core/validate');
6
+ *
7
+ * const errors = validate(req.body, {
8
+ * phone: [rules.required('手机号'), rules.phone()],
9
+ * password: [rules.required('密码'), rules.minLength(6, '密码至少6位')],
10
+ * email: [rules.email()],
11
+ * });
12
+ * if (errors) return res.status(400).json({ code: 400, message: errors[0] });
13
+ */
14
+
15
+ /**
16
+ * 校验数据,返回第一个错误消息,通过返回 null
17
+ *
18
+ * @param {Object} data - 待校验数据
19
+ * @param {Object} schema - { field: [ruleFn, ...] }
20
+ * @returns {string|null} - 第一个错误消息
21
+ */
22
+ function validate(data, schema) {
23
+ for (const [field, fieldRules] of Object.entries(schema)) {
24
+ const value = data[field];
25
+ for (const rule of fieldRules) {
26
+ const err = rule(value, field);
27
+ if (err) return err;
28
+ }
29
+ }
30
+ return null;
31
+ }
32
+
33
+ const rules = {
34
+ required: (label = '此字段') => (val) =>
35
+ (val === undefined || val === null || String(val).trim() === '')
36
+ ? `${label}不能为空` : null,
37
+
38
+ phone: (label = '手机号') => (val) => {
39
+ if (!val) return null; // 非必填
40
+ return /^1[3-9]\d{9}$/.test(String(val)) ? null : `${label}格式不正确`;
41
+ },
42
+
43
+ email: (label = '邮箱') => (val) => {
44
+ if (!val) return null;
45
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(val)) ? null : `${label}格式不正确`;
46
+ },
47
+
48
+ minLength: (min, label) => (val) => {
49
+ if (!val) return null;
50
+ return String(val).length >= min ? null : `${label || '值'}至少${min}个字符`;
51
+ },
52
+
53
+ maxLength: (max, label) => (val) => {
54
+ if (!val) return null;
55
+ return String(val).length <= max ? null : `${label || '值'}最多${max}个字符`;
56
+ },
57
+
58
+ isNumber: (label = '值') => (val) => {
59
+ if (val === undefined || val === null) return null;
60
+ return !isNaN(Number(val)) ? null : `${label}必须是数字`;
61
+ },
62
+
63
+ isInt: (label = '值') => (val) => {
64
+ if (val === undefined || val === null) return null;
65
+ return Number.isInteger(Number(val)) ? null : `${label}必须是整数`;
66
+ },
67
+
68
+ oneOf: (allowed, label) => (val) => {
69
+ if (!val) return null;
70
+ return allowed.includes(val) ? null : `${label || '值'}无效,可选: ${allowed.join(', ')}`;
71
+ },
72
+ };
73
+
74
+ module.exports = { validate, rules };