@ai0x0/utils 0.6.0 → 0.6.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.
Files changed (49) hide show
  1. package/es/backend/actions/create-delete-action.d.ts +2 -3
  2. package/es/backend/actions/create-delete-action.js +8 -44
  3. package/es/backend/actions/create-put-action.d.ts +1 -1
  4. package/es/backend/actions/create-put-action.js +15 -39
  5. package/es/backend/actions/get-list-query-core.d.ts +46 -0
  6. package/es/backend/actions/get-list-query-core.js +236 -0
  7. package/es/backend/actions/get-list-query.d.ts +5 -18
  8. package/es/backend/actions/get-list-query.js +20 -220
  9. package/es/backend/actions/write-action-core.d.ts +18 -0
  10. package/es/backend/actions/write-action-core.js +119 -0
  11. package/es/backend/schemas/common.d.ts +112 -0
  12. package/es/backend/schemas/common.js +158 -0
  13. package/es/backend/schemas/index.d.ts +735 -364
  14. package/es/backend/schemas/index.js +8 -139
  15. package/es/backend/sqlite/actions/create-delete-action.d.ts +1 -2
  16. package/es/backend/sqlite/actions/create-delete-action.js +7 -43
  17. package/es/backend/sqlite/actions/create-put-action.d.ts +1 -1
  18. package/es/backend/sqlite/actions/create-put-action.js +13 -36
  19. package/es/backend/sqlite/actions/get-list-query.d.ts +4 -9
  20. package/es/backend/sqlite/actions/get-list-query.js +20 -217
  21. package/es/backend/sqlite/errors.d.ts +1 -4
  22. package/es/backend/sqlite/errors.js +6 -31
  23. package/es/backend/sqlite/schemas/index.d.ts +1 -111
  24. package/es/backend/sqlite/schemas/index.js +8 -139
  25. package/lib/backend/actions/create-delete-action.d.ts +2 -3
  26. package/lib/backend/actions/create-delete-action.js +2 -14
  27. package/lib/backend/actions/create-put-action.d.ts +1 -1
  28. package/lib/backend/actions/create-put-action.js +3 -16
  29. package/lib/backend/actions/get-list-query-core.d.ts +46 -0
  30. package/lib/backend/actions/get-list-query-core.js +151 -0
  31. package/lib/backend/actions/get-list-query.d.ts +5 -18
  32. package/lib/backend/actions/get-list-query.js +16 -141
  33. package/lib/backend/actions/write-action-core.d.ts +18 -0
  34. package/lib/backend/actions/write-action-core.js +70 -0
  35. package/lib/backend/schemas/common.d.ts +112 -0
  36. package/lib/backend/schemas/common.js +112 -0
  37. package/lib/backend/schemas/index.d.ts +735 -364
  38. package/lib/backend/schemas/index.js +12 -83
  39. package/lib/backend/sqlite/actions/create-delete-action.d.ts +1 -2
  40. package/lib/backend/sqlite/actions/create-delete-action.js +2 -14
  41. package/lib/backend/sqlite/actions/create-put-action.d.ts +1 -1
  42. package/lib/backend/sqlite/actions/create-put-action.js +3 -16
  43. package/lib/backend/sqlite/actions/get-list-query.d.ts +4 -9
  44. package/lib/backend/sqlite/actions/get-list-query.js +16 -141
  45. package/lib/backend/sqlite/errors.d.ts +1 -4
  46. package/lib/backend/sqlite/errors.js +2 -8
  47. package/lib/backend/sqlite/schemas/index.d.ts +1 -111
  48. package/lib/backend/sqlite/schemas/index.js +12 -83
  49. package/package.json +1 -1
@@ -4,12 +4,6 @@ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t =
4
4
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
5
5
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
6
6
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
7
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
9
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
11
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
12
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13
7
  import { z } from "zod";
14
8
  import { pgTable, timestamp, uuid } from "drizzle-orm/pg-core";
15
9
  import { createInsertSchema, createSelectSchema, createUpdateSchema } from "drizzle-zod";
@@ -40,141 +34,16 @@ export var basicFields = {
40
34
  updatedAt: updatedAt()
41
35
  };
42
36
 
43
- /**
44
- * 业务侧 insert schema 需要从 drizzle-zod 生成的 schema 中排除的基础字段。
45
- * 这些字段由后端在 createPostAction 中自动写入。
46
- *
47
- * 使用方式(在业务 schema 中):
48
- * const insertFooSchema = createInsertSchema(foos)
49
- * .omit(BASIC_INSERT_OMIT)
50
- * .extend({ ... });
51
- *
52
- * 说明:上游导出为 const 而不是 helper function,是为了避免经过泛型
53
- * wrapper 后 TS 把 drizzle-zod 推导出的深层条件 Shape 归约成 Omit,
54
- * 从而在下游 `.extend(...)` 时丢失原有字段类型。
55
- */
56
- export var BASIC_INSERT_OMIT = {
57
- id: true,
58
- creatorId: true,
59
- editorId: true,
60
- accessedAt: true,
61
- createdAt: true,
62
- updatedAt: true
63
- };
64
-
65
- /**
66
- * 业务侧 update schema 需要从 drizzle-zod 生成的 schema 中排除的基础字段。
67
- * update 保留 id(随后用 `.required({ id: true })` 变成必填),其余由
68
- * 后端 createPutAction 自动维护。
69
- */
70
- export var BASIC_UPDATE_OMIT = {
71
- creatorId: true,
72
- editorId: true,
73
- accessedAt: true,
74
- createdAt: true,
75
- updatedAt: true
76
- };
77
-
78
- // =============================================================================
79
- // 列表查询字段
80
- // =============================================================================
81
- // 说明写成 `.describe()` 而不是行末注释:注释只有读源码的人看得到,而这七个字段会出现在每一个
82
- // list 端点的 OpenAPI spec 里,再从那里流进生成的 client 与 CLI 文档。写成注释的代价是下游只能
83
- // 自己再手写一份 —— 那份必然会漂,而且漂了没有任何东西会报错。
84
- //
85
- // 类型是 string 而不是 number:query 参数在线上只有字符串,服务端收下之后才转数字。默认值也
86
- // 因此是 "1" / "10"。
87
- export var queryListSchema = function queryListSchema(schema) {
88
- return z.object({
89
- current: z.string().optional().default("1").describe("Page number, starting at 1."),
90
- pageSize: z.string().optional().default("10").describe("Rows per page. Omitting it yields only 10 — pass a larger value to get the whole set."),
91
- createdAtFrom: z.string().optional().describe("Keep only rows created at or after this instant (ISO 8601, e.g. 2026-08-01T00:00:00Z)."),
92
- createdAtTo: z.string().optional().describe("Keep only rows created at or before this instant."),
93
- orderBy: z.string().optional().describe("Column to sort by — a column name of this resource (createdAt / updatedAt and the like)."),
94
- creatorId: z.string().optional().describe("Keep only rows created by this user. Useful in shared spaces to filter down to one member."),
95
- orderDir: z.enum(["asc", "desc"]).optional().describe("Sort ascending or descending.")
96
- }).merge(schema);
97
- };
98
-
99
37
  // =============================================================================
100
- // 列表返回字段
38
+ // 与方言无关的那几份助手
101
39
  // =============================================================================
102
- // 这两个字段出现在**每一个** list 端点的响应里,所以说明写在这儿一次就够 —— 下游那边它们是
103
- // 逐个 list 命令重复一遍的(在一个 101 端点的项目上是 24 行空白)。
104
- export var listBodySchema = function listBodySchema(schema) {
105
- return z.object({
106
- total: z.number().describe("Total number of rows matching the filters — not the length of `data`. Use it to decide whether another page exists."),
107
- data: z.array(schema).describe("This page's rows.")
108
- });
109
- };
110
-
111
- // =============================================================================
112
- // 给基础字段挂说明
113
- // =============================================================================
114
- // basicFields 是 drizzle 列,而 drizzle 列没有「描述」这个概念 —— 所以说明只能挂在
115
- // drizzle-zod 出来的 schema 上。值得做是因为这六个字段出现在**每一张表**的 select schema 里:
116
- // 一处写完,所有 list / get 端点的返回字段表都有了(在 do-tv 上是 173 行)。
117
- //
118
- // 一律只挂元数据,**不换类型**:`.describe()` / `.meta()` 返回的是带元数据的克隆,校验行为一模
119
- // 一样。selectSchema 是有人拿去 safeParse 的(本包自己的测试就在用 Date 校验它),换类型等于改
120
- // 这个包的契约。
121
- //
122
- // 时间戳那三列额外用 `.meta()` 补上 JSON Schema 表示,因为不补就是错的:drizzle-zod 给的是
123
- // `z.date()`,而 `Date` 在 JSON Schema 里表达不出来,于是这三个字段在 spec 里是**空对象** ——
124
- // 没有 `type`,照 spec 生成的 client / CLI 只能得到 `unknown`。而线上根本不可能是 Date:响应一经
125
- // JSON 序列化就是 ISO 8601 字符串。
126
- //
127
- // `.meta({ type, format })` 恰好只改「怎么描述」不改「怎么校验」:spec 里成为
128
- // `{"type":"string","format":"date-time"}`,而 `safeParse(new Date())` 照样通过。
129
- // 不用 `z.iso.datetime()` 换掉它,是因为那既改了校验(不再收 Date),又会往 JSON Schema 里塞一条
130
- // 380 字节的正则 —— 乘上每张表几十 KB,而 `format` 已经把「按日期时间解析」说清楚了。
131
- var BASIC_FIELD_NOTES = {
132
- creatorId: "User id of the creator. Stamped by the server; clients cannot send it.",
133
- editorId: "User id of whoever changed this row last. Stamped by the server; clients cannot send it.",
134
- id: "Primary key of this row (uuid)."
135
- };
136
- var BASIC_TIMESTAMP_NOTES = {
137
- accessedAt: "When this row was last accessed.",
138
- createdAt: "When this row was created.",
139
- updatedAt: "When this row was last modified."
140
- };
141
-
142
- /**
143
- * 给 schema 上已有的字段挂说明。字段不在这个 schema 里就跳过 —— 同一张表的
144
- * insert / update / select 三份含的列不一样(basicFields 只在 select 里),一份说明表要能同时
145
- * 喂给三者,就不能对「字段一定存在」有要求。**不给不存在的字段凭空造一个。**
146
- */
147
- export var describeFields = function describeFields(schema, notes) {
148
- var overlay = {};
149
- for (var _i = 0, _Object$entries = Object.entries(notes); _i < _Object$entries.length; _i++) {
150
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
151
- field = _Object$entries$_i[0],
152
- note = _Object$entries$_i[1];
153
- var existing = schema.shape[field];
154
- if (existing) {
155
- overlay[field] = existing.describe(note);
156
- }
157
- }
158
- return Object.keys(overlay).length ? schema.extend(overlay) : schema;
159
- };
160
- var describeBasicFields = function describeBasicFields(schema) {
161
- var withNotes = describeFields(schema, BASIC_FIELD_NOTES);
162
- var overlay = {};
163
- for (var _i2 = 0, _Object$entries2 = Object.entries(BASIC_TIMESTAMP_NOTES); _i2 < _Object$entries2.length; _i2++) {
164
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
165
- field = _Object$entries2$_i[0],
166
- note = _Object$entries2$_i[1];
167
- var existing = withNotes.shape[field];
168
- if (existing) {
169
- overlay[field] = existing.meta({
170
- description: note,
171
- format: "date-time",
172
- type: "string"
173
- });
174
- }
175
- }
176
- return Object.keys(overlay).length ? withNotes.extend(overlay) : withNotes;
177
- };
40
+ // BASIC_INSERT_OMIT / BASIC_UPDATE_OMIT / queryListSchema / listBodySchema / describeFields
41
+ // 都只碰 zod,两套方言逐字相同 —— 实现搬去了 schemas/common,这里原样转出去,调用方的
42
+ // import 路径一个字都不用改。
43
+ // createTableSchema 自己也要用其中几个 —— `export ... from` 只转发、不把名字带进
44
+ // 本地作用域,所以这里还得再 import 一次。
45
+ import { describeBasicFields, describeFields, queryListSchema } from "./common.js";
46
+ export { BASIC_INSERT_OMIT, BASIC_UPDATE_OMIT, describeFields, listBodySchema, queryListSchema } from "./common.js";
178
47
 
179
48
  // =============================================================================
180
49
  // 建表 —— 表 + 5 份 zod schema
@@ -1,10 +1,9 @@
1
1
  import { BaseTable } from "../types.js";
2
- import { ScopeArg } from "../../scope.js";
3
2
  export declare function createDeleteAction<TTable extends BaseTable>({ table, db, }: {
4
3
  db: any;
5
4
  table: TTable;
6
5
  }): ({ id }: {
7
6
  id: string;
8
7
  }, { scope }: {
9
- scope: ScopeArg;
8
+ scope: import("../../index.js").ScopeArg;
10
9
  }) => Promise<any>;
@@ -1,47 +1,11 @@
1
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
- import { and, eq } from "drizzle-orm";
6
- import { NO_SCOPE, scopeCondition } from "../../scope.js";
7
- import { HttpError } from "../errors.js";
1
+ // 删一行。实现与 pg 那套共用,见 backend/actions/write-action-core。
2
+
3
+ import { createDeleteActionCore } from "../../actions/write-action-core.js";
8
4
  export function createDeleteAction(_ref) {
9
5
  var table = _ref.table,
10
6
  db = _ref.db;
11
- return /*#__PURE__*/function () {
12
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2, _ref3) {
13
- var id, scope, guard, rows;
14
- return _regeneratorRuntime().wrap(function _callee$(_context) {
15
- while (1) switch (_context.prev = _context.next) {
16
- case 0:
17
- id = _ref2.id;
18
- scope = _ref3.scope;
19
- if (id) {
20
- _context.next = 4;
21
- break;
22
- }
23
- throw new HttpError(400, "缺少 id");
24
- case 4:
25
- guard = scopeCondition(table, scope);
26
- _context.next = 7;
27
- return db.delete(table).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
28
- case 7:
29
- rows = _context.sent;
30
- if (!(rows.length === 0 && scope !== NO_SCOPE)) {
31
- _context.next = 10;
32
- break;
33
- }
34
- throw new HttpError(404, "未找到删除对象,或没有权限");
35
- case 10:
36
- return _context.abrupt("return", rows);
37
- case 11:
38
- case "end":
39
- return _context.stop();
40
- }
41
- }, _callee);
42
- }));
43
- return function (_x, _x2) {
44
- return _ref4.apply(this, arguments);
45
- };
46
- }();
7
+ return createDeleteActionCore({
8
+ db: db,
9
+ table: table
10
+ });
47
11
  }
@@ -4,6 +4,6 @@ export declare function createPutAction<TTable extends BaseTable>({ db, table, }
4
4
  bodySchema: any;
5
5
  db: any;
6
6
  table: TTable;
7
- }): (body: Record<string, unknown>, { scope }: {
7
+ }): (body: Record<string, unknown>, options: {
8
8
  scope: ScopeArg;
9
9
  }) => Promise<any>;
@@ -1,56 +1,33 @@
1
1
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
2
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
4
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
5
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
6
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
7
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
8
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
9
3
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
10
4
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
11
- import { transformBody } from "./transform-body.js";
12
- import { and, eq } from "drizzle-orm";
13
- import { NO_SCOPE, scopeCondition } from "../../scope.js";
14
- import { HttpError } from "../errors.js";
5
+ // 改一行。实现与 pg 那套共用,见 backend/actions/write-action-core(三条安全性质写在那儿)。
6
+
7
+ import { createPutActionCore } from "../../actions/write-action-core.js";
15
8
  export function createPutAction(_ref) {
16
9
  var db = _ref.db,
17
10
  table = _ref.table;
11
+ var run = createPutActionCore({
12
+ db: db,
13
+ table: table
14
+ });
15
+ // 返回 any 而不是核心那个 unknown —— 这一栏改动前就是 any,收紧它对下游是破坏性的,
16
+ // 而这次改动的意图是「实现合并」,不是「顺手改公开类型」。
18
17
  return /*#__PURE__*/function () {
19
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(body, _ref2) {
20
- var scope, id, guard, _yield$db$update$set$, _yield$db$update$set$2, data;
18
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(body, options) {
21
19
  return _regeneratorRuntime().wrap(function _callee$(_context) {
22
20
  while (1) switch (_context.prev = _context.next) {
23
21
  case 0:
24
- scope = _ref2.scope;
25
- id = body.id;
26
- if (id) {
27
- _context.next = 4;
28
- break;
29
- }
30
- throw new HttpError(400, "缺少 id");
31
- case 4:
32
- guard = scopeCondition(table, scope);
33
- _context.next = 7;
34
- return db.update(table).set(transformBody(body)).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
35
- case 7:
36
- _yield$db$update$set$ = _context.sent;
37
- _yield$db$update$set$2 = _slicedToArray(_yield$db$update$set$, 1);
38
- data = _yield$db$update$set$2[0];
39
- if (!(!data && scope !== NO_SCOPE)) {
40
- _context.next = 12;
41
- break;
42
- }
43
- throw new HttpError(404, "未找到编辑对象,或没有权限");
44
- case 12:
45
- return _context.abrupt("return", data);
46
- case 13:
22
+ return _context.abrupt("return", run(body, options));
23
+ case 1:
47
24
  case "end":
48
25
  return _context.stop();
49
26
  }
50
27
  }, _callee);
51
28
  }));
52
29
  return function (_x, _x2) {
53
- return _ref3.apply(this, arguments);
30
+ return _ref2.apply(this, arguments);
54
31
  };
55
32
  }();
56
33
  }
@@ -1,19 +1,14 @@
1
- import { ScopeArg } from "../../scope.js";
2
1
  import { BaseTable, GetListRelations } from "../types.js";
3
2
  import { SelectedFields } from "drizzle-orm/sqlite-core/query-builders/select.types";
4
- export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>({ db, fields, jsonArrayFields, params, scope, relations, table, }: {
3
+ import { ScopeArg } from "../../scope.js";
4
+ import { type ListQueryParams } from "../../actions/get-list-query-core.js";
5
+ export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>(args: {
5
6
  db: any;
6
7
  fields: TSelection;
7
8
  jsonArrayFields?: string[];
8
9
  /** 必填。与 pg 那套同义,见 backend/scope.ts。 */
9
10
  scope: ScopeArg;
10
- params: {
11
- [field: string]: unknown;
12
- orderBy?: keyof BaseTable;
13
- orderDir?: "asc" | "desc";
14
- page?: number;
15
- pageSize?: number;
16
- };
11
+ params: ListQueryParams;
17
12
  relations?: GetListRelations;
18
13
  table: TTable;
19
14
  }): {
@@ -1,220 +1,23 @@
1
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
- var _templateObject, _templateObject2, _templateObject3;
3
- var _excluded = ["page", "pageSize", "orderBy", "orderDir"];
4
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
5
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
7
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
1
+ var _templateObject;
8
2
  function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
9
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
10
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
11
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
12
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
13
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
14
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
15
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
16
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
17
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
18
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
19
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
20
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
21
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
22
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
23
- import { scopeCondition } from "../../scope.js";
24
- import { and, asc, desc, eq, gte, like, inArray, lte, or, sql } from "drizzle-orm";
25
- export function getListQuery(_ref) {
26
- var db = _ref.db,
27
- fields = _ref.fields,
28
- jsonArrayFields = _ref.jsonArrayFields,
29
- params = _ref.params,
30
- scope = _ref.scope,
31
- relations = _ref.relations,
32
- table = _ref.table;
33
- var _params$page = params.page,
34
- page = _params$page === void 0 ? 1 : _params$page,
35
- _params$pageSize = params.pageSize,
36
- pageSize = _params$pageSize === void 0 ? 10 : _params$pageSize,
37
- _params$orderBy = params.orderBy,
38
- orderBy = _params$orderBy === void 0 ? "createdAt" : _params$orderBy,
39
- _params$orderDir = params.orderDir,
40
- orderDir = _params$orderDir === void 0 ? "desc" : _params$orderDir,
41
- filters = _objectWithoutProperties(params, _excluded);
42
-
43
- // 构建基础查询
44
- function buildBaseQuery(table, fields, relations) {
45
- var queryFields = _objectSpread({}, fields);
46
-
47
- // 添加关联字段
48
- if (relations !== null && relations !== void 0 && relations.length) {
49
- var _iterator = _createForOfIteratorHelper(relations),
50
- _step;
51
- try {
52
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
53
- var select = _step.value.select;
54
- queryFields = _objectSpread(_objectSpread({}, queryFields), select);
55
- }
56
- } catch (err) {
57
- _iterator.e(err);
58
- } finally {
59
- _iterator.f();
60
- }
61
- }
62
- var query = db.select(queryFields).from(table);
63
-
64
- // 添加分组
65
- if (relations !== null && relations !== void 0 && relations.length) {
66
- query.groupBy.apply(query, [table.id].concat(_toConsumableArray(relations.filter(function (_ref2) {
67
- var groupBy = _ref2.groupBy;
68
- return groupBy;
69
- }).filter(function (_ref3) {
70
- var table = _ref3.table;
71
- return table;
72
- }).map(function (_ref4) {
73
- var table = _ref4.table;
74
- return table.id;
75
- }))));
76
- }
77
- return query;
78
- }
79
-
80
- // 查找目标列
81
- function findTargetColumn(key, table, relations) {
82
- var _concat$find;
83
- return (_concat$find = [table].concat((relations === null || relations === void 0 ? void 0 : relations.filter(function (_ref5) {
84
- var table = _ref5.table;
85
- return table;
86
- }).map(function (_ref6) {
87
- var table = _ref6.table;
88
- return table;
89
- })) || []).find(function (table) {
90
- return table[key];
91
- })) === null || _concat$find === void 0 ? void 0 : _concat$find[key];
92
- }
93
-
94
- // 添加条件
95
- function addCondition(conditions, key, value, targetColumn) {
96
- var isIdField = /id/i.test(key);
97
- var isJsonArray = jsonArrayFields === null || jsonArrayFields === void 0 ? void 0 : jsonArrayFields.includes(key);
98
- if (typeof value === "string") {
99
- if (value.includes(",")) {
100
- // 处理多值
101
- var values = value.split(",").map(function (val) {
102
- return val.trim();
103
- }).filter(Boolean);
104
- if (values.length > 0) {
105
- if (isJsonArray) {
106
- // 处理 JSON 数组字段
107
- conditions.push(sql(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n EXISTS (\n SELECT 1 FROM json_each(", ") tag\n WHERE tag.value LIKE ", "\n )\n "])), targetColumn, "%".concat(values[0], "%")));
108
- } else if (isIdField) {
109
- conditions.push(inArray(targetColumn, values));
110
- } else {
111
- conditions.push(or.apply(void 0, _toConsumableArray(values.map(function (val) {
112
- return like(targetColumn, "%".concat(val, "%"));
113
- }))));
114
- }
115
- }
116
- } else {
117
- // 处理单值
118
- if (isJsonArray) {
119
- // 处理 JSON 数组字段
120
- conditions.push(sql(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n EXISTS (\n SELECT 1 FROM json_each(", ") tag\n WHERE tag.value LIKE ", "\n )\n "])), targetColumn, "%".concat(value, "%")));
121
- } else if (isIdField) {
122
- conditions.push(eq(targetColumn, value));
123
- } else {
124
- conditions.push(like(targetColumn, "%".concat(value, "%")));
125
- }
126
- }
127
- } else {
128
- conditions.push(eq(targetColumn, value));
129
- }
130
- }
131
-
132
- // 构建查询条件
133
- function buildConditions(filters, table, relations) {
134
- var conditions = [];
135
-
136
- // 处理过滤条件
137
- for (var _i = 0, _Object$entries = Object.entries(filters); _i < _Object$entries.length; _i++) {
138
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
139
- key = _Object$entries$_i[0],
140
- value = _Object$entries$_i[1];
141
- if (!value) {
142
- continue;
143
- }
144
-
145
- // 处理日期范围字段
146
- if (key.endsWith("AtFrom") || key.endsWith("AtTo")) {
147
- var baseFieldName = key.replace(/(AtFrom|AtTo)$/, "");
148
- var _targetColumn = findTargetColumn("".concat(baseFieldName, "At"), table, relations);
149
- if (!_targetColumn) {
150
- continue;
151
- }
152
- if (key.endsWith("AtFrom")) {
153
- conditions.push(gte(_targetColumn, new Date(value)));
154
- } else if (key.endsWith("AtTo")) {
155
- conditions.push(lte(_targetColumn, new Date(value)));
156
- }
157
- continue;
158
- }
159
-
160
- // 处理其他普通过滤条件
161
- var targetColumn = findTargetColumn(key, table, relations);
162
- if (!targetColumn) {
163
- continue;
164
- }
165
- addCondition(conditions, key, value, targetColumn);
166
- }
167
- return conditions;
168
- }
169
-
170
- // 构建排序
171
- function buildOrderBy(table, orderBy, orderDir) {
172
- var orderColumn = table[orderBy];
173
- return orderDir === "asc" ? asc(orderColumn) : desc(orderColumn);
3
+ // ==============================================================================
4
+ // 列表查询(SQLite)
5
+ // ==============================================================================
6
+ // 实现在 backend/actions/get-list-query-core,与 pg 那套共用。这里只给它两条 sqlite 专属的
7
+ // 原语:sqlite 的 like 本来就不区分大小写(没有 ilike),JSON 数组用 json_each 展开。
8
+
9
+ import { like, sql } from "drizzle-orm";
10
+ import { createGetListQuery } from "../../actions/get-list-query-core.js";
11
+ var run = createGetListQuery({
12
+ contains: function contains(column, keyword) {
13
+ return like(column, "%".concat(keyword, "%"));
14
+ },
15
+ // json_each 展开出来的行里,值在 tag.value 上(pg 那个 _text 变体是直接给字符串的)——
16
+ // 这是两边唯一一处连字段名都不同的地方。
17
+ jsonArrayContains: function jsonArrayContains(column, keyword) {
18
+ return sql(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n EXISTS (\n SELECT 1 FROM json_each(", ") tag\n WHERE tag.value LIKE ", "\n )\n "])), column, "%".concat(keyword, "%"));
174
19
  }
175
-
176
- // 构建基础查询
177
- var baseQuery = buildBaseQuery(table, fields, relations);
178
-
179
- // 构建条件
180
- // 作用域先加,且不受「空值跳过」那条规矩管(见 backend/scope.ts 第 1 条)。
181
- var scopeSql = scopeCondition(table, scope);
182
- var conditions = scopeSql ? [scopeSql] : [];
183
- conditions.push.apply(conditions, _toConsumableArray(buildConditions(filters, table, relations)));
184
-
185
- // 构建主查询
186
- var query = baseQuery.where(conditions.length > 0 ? and.apply(void 0, conditions) : undefined).orderBy(buildOrderBy(table, orderBy, orderDir)).limit(pageSize).offset((page - 1) * pageSize);
187
-
188
- // 构建计数查询(优化后)
189
- var countQuery = db.select({
190
- count: sql(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["COUNT(DISTINCT ", ")"])), table.id)
191
- }).from(table).where(conditions.length > 0 ? and.apply(void 0, conditions) : undefined);
192
-
193
- // 添加关联
194
- if (relations !== null && relations !== void 0 && relations.length) {
195
- var _iterator2 = _createForOfIteratorHelper(relations),
196
- _step2;
197
- try {
198
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
199
- var _step2$value = _step2.value,
200
- relationTable = _step2$value.table,
201
- joinSql = _step2$value.sql;
202
- if (relationTable) {
203
- query.leftJoin(relationTable, joinSql);
204
- countQuery.leftJoin(relationTable, joinSql);
205
- }
206
- }
207
- } catch (err) {
208
- _iterator2.e(err);
209
- } finally {
210
- _iterator2.f();
211
- }
212
- }
213
-
214
- // console.log(query.prepare("a").getQuery());
215
-
216
- return {
217
- countQuery: countQuery,
218
- query: query
219
- };
20
+ });
21
+ export function getListQuery(args) {
22
+ return run(args);
220
23
  }
@@ -1,4 +1 @@
1
- export declare class HttpError extends Error {
2
- status: number;
3
- constructor(status: number, message: string);
4
- }
1
+ export { HttpError } from "../errors.js";