@ai0x0/utils 0.5.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 (59) 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/route-operation/operation-common.d.ts +13 -1
  12. package/es/backend/route-operation/operation-common.js +25 -0
  13. package/es/backend/route-operation/read-operation-core.js +46 -33
  14. package/es/backend/route-operation/write-operation-core.d.ts +3 -1
  15. package/es/backend/route-operation/write-operation-core.js +69 -26
  16. package/es/backend/schemas/common.d.ts +112 -0
  17. package/es/backend/schemas/common.js +158 -0
  18. package/es/backend/schemas/index.d.ts +735 -364
  19. package/es/backend/schemas/index.js +8 -139
  20. package/es/backend/sqlite/actions/create-delete-action.d.ts +1 -2
  21. package/es/backend/sqlite/actions/create-delete-action.js +7 -43
  22. package/es/backend/sqlite/actions/create-put-action.d.ts +1 -1
  23. package/es/backend/sqlite/actions/create-put-action.js +13 -36
  24. package/es/backend/sqlite/actions/get-list-query.d.ts +4 -9
  25. package/es/backend/sqlite/actions/get-list-query.js +20 -217
  26. package/es/backend/sqlite/errors.d.ts +1 -4
  27. package/es/backend/sqlite/errors.js +6 -31
  28. package/es/backend/sqlite/schemas/index.d.ts +1 -111
  29. package/es/backend/sqlite/schemas/index.js +8 -139
  30. package/lib/backend/actions/create-delete-action.d.ts +2 -3
  31. package/lib/backend/actions/create-delete-action.js +2 -14
  32. package/lib/backend/actions/create-put-action.d.ts +1 -1
  33. package/lib/backend/actions/create-put-action.js +3 -16
  34. package/lib/backend/actions/get-list-query-core.d.ts +46 -0
  35. package/lib/backend/actions/get-list-query-core.js +151 -0
  36. package/lib/backend/actions/get-list-query.d.ts +5 -18
  37. package/lib/backend/actions/get-list-query.js +16 -141
  38. package/lib/backend/actions/write-action-core.d.ts +18 -0
  39. package/lib/backend/actions/write-action-core.js +70 -0
  40. package/lib/backend/route-operation/operation-common.d.ts +13 -1
  41. package/lib/backend/route-operation/operation-common.js +8 -0
  42. package/lib/backend/route-operation/read-operation-core.js +14 -4
  43. package/lib/backend/route-operation/write-operation-core.d.ts +3 -1
  44. package/lib/backend/route-operation/write-operation-core.js +24 -4
  45. package/lib/backend/schemas/common.d.ts +112 -0
  46. package/lib/backend/schemas/common.js +112 -0
  47. package/lib/backend/schemas/index.d.ts +735 -364
  48. package/lib/backend/schemas/index.js +12 -83
  49. package/lib/backend/sqlite/actions/create-delete-action.d.ts +1 -2
  50. package/lib/backend/sqlite/actions/create-delete-action.js +2 -14
  51. package/lib/backend/sqlite/actions/create-put-action.d.ts +1 -1
  52. package/lib/backend/sqlite/actions/create-put-action.js +3 -16
  53. package/lib/backend/sqlite/actions/get-list-query.d.ts +4 -9
  54. package/lib/backend/sqlite/actions/get-list-query.js +16 -141
  55. package/lib/backend/sqlite/errors.d.ts +1 -4
  56. package/lib/backend/sqlite/errors.js +2 -8
  57. package/lib/backend/sqlite/schemas/index.d.ts +1 -111
  58. package/lib/backend/sqlite/schemas/index.js +12 -83
  59. package/package.json +1 -1
@@ -1,11 +1,10 @@
1
1
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
2
  import { BaseTable } from "../types.js";
3
- import { ScopeArg } from "../scope.js";
4
3
  export declare function createDeleteAction<TTable extends BaseTable>({ table, db, }: {
5
4
  db: NodePgDatabase<Record<string, unknown>>;
6
5
  table: TTable;
7
6
  }): ({ id }: {
8
7
  id: string;
9
8
  }, { scope }: {
10
- scope: ScopeArg;
11
- }) => Promise<TTable["$inferSelect"] extends infer T ? T extends TTable["$inferSelect"] ? T extends undefined ? QueryResult<import("drizzle-orm").Assume<this["row"], QueryResultRow>> : T[] : never : never>;
9
+ scope: import("..").ScopeArg;
10
+ }) => Promise<any>;
@@ -1,48 +1,12 @@
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
+ // 删一行。实现(含三条安全性质:归属写进 where、作用域必填、不区分「不存在」与「不归你」)
2
+ // 在 write-action-core,与 sqlite 共用。
3
+
4
+ import { createDeleteActionCore } from "./write-action-core.js";
8
5
  export function createDeleteAction(_ref) {
9
6
  var table = _ref.table,
10
7
  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
- // 归属写进 DELETE 的 where,不先查后删(理由同 create-put-action)。
26
- guard = scopeCondition(table, scope);
27
- _context.next = 7;
28
- return db.delete(table).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
29
- case 7:
30
- rows = _context.sent;
31
- if (!(rows.length === 0 && scope !== NO_SCOPE)) {
32
- _context.next = 10;
33
- break;
34
- }
35
- throw new HttpError(404, "未找到删除对象,或没有权限");
36
- case 10:
37
- return _context.abrupt("return", rows);
38
- case 11:
39
- case "end":
40
- return _context.stop();
41
- }
42
- }, _callee);
43
- }));
44
- return function (_x, _x2) {
45
- return _ref4.apply(this, arguments);
46
- };
47
- }();
8
+ return createDeleteActionCore({
9
+ db: db,
10
+ table: table
11
+ });
48
12
  }
@@ -6,6 +6,6 @@ export declare function createPutAction<T extends ZodSchema, TTable extends Base
6
6
  bodySchema: T;
7
7
  db: NodePgDatabase<Record<string, unknown>>;
8
8
  table: TTable;
9
- }): (body: Partial<z.infer<T>> & Record<string, unknown>, { scope }: {
9
+ }): (body: Partial<z.infer<T>> & Record<string, unknown>, options: {
10
10
  scope: ScopeArg;
11
11
  }) => Promise<z.infer<T>>;
@@ -1,59 +1,35 @@
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
+ // 改一行。实现(含三条安全性质)在 write-action-core,与 sqlite 共用;这里只把签名收紧到
6
+ // pg 的类型上 —— 核心为了同时喂两套方言,db 与返回值那两栏是宽的,调用方不该跟着变宽。
7
+
8
+ import { createPutActionCore } from "./write-action-core.js";
15
9
  export function createPutAction(_ref) {
16
10
  var db = _ref.db,
17
11
  table = _ref.table;
12
+ var run = createPutActionCore({
13
+ db: db,
14
+ table: table
15
+ });
18
16
  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;
17
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(body, options) {
21
18
  return _regeneratorRuntime().wrap(function _callee$(_context) {
22
19
  while (1) switch (_context.prev = _context.next) {
23
20
  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
- // 归属条件直接写进 UPDATE 的 where,而不是「先查一次确认归属、再无条件更新」。
33
- // 先查后改有两个问题:多一次往返,以及那一查一改之间归属可能已经变了(转移给团队、
34
- // 踢出成员)。一条语句里带上归属,改不到就是改不到。
35
- guard = scopeCondition(table, scope);
36
- _context.next = 7;
37
- return db.update(table).set(transformBody(body)).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
38
- case 7:
39
- _yield$db$update$set$ = _context.sent;
40
- _yield$db$update$set$2 = _slicedToArray(_yield$db$update$set$, 1);
41
- data = _yield$db$update$set$2[0];
42
- if (!(!data && scope !== NO_SCOPE)) {
43
- _context.next = 12;
44
- break;
45
- }
46
- throw new HttpError(404, "未找到编辑对象,或没有权限");
47
- case 12:
48
- return _context.abrupt("return", data);
49
- case 13:
21
+ _context.next = 2;
22
+ return run(body, options);
23
+ case 2:
24
+ return _context.abrupt("return", _context.sent);
25
+ case 3:
50
26
  case "end":
51
27
  return _context.stop();
52
28
  }
53
29
  }, _callee);
54
30
  }));
55
31
  return function (_x, _x2) {
56
- return _ref3.apply(this, arguments);
32
+ return _ref2.apply(this, arguments);
57
33
  };
58
34
  }();
59
35
  }
@@ -0,0 +1,46 @@
1
+ import { Column, SQL } from "drizzle-orm";
2
+ import { ScopeArg } from "../scope.js";
3
+ /**
4
+ * 核心用得到表的哪一部分:只有 `id`(计数与分组要它)和「按列名取列」。
5
+ * 两棵树的 BaseTable 都满足它,而 dialect 各自的 Table 类型不必进来。
6
+ */
7
+ export interface ListQueryTable {
8
+ id: Column;
9
+ }
10
+ export interface ListQueryRelation {
11
+ groupBy?: boolean;
12
+ select?: Record<string, unknown>;
13
+ sql?: SQL;
14
+ table?: ListQueryTable;
15
+ }
16
+ /** 两套方言之间**全部**的差异。加第三种数据库时要写的也只有这两条。 */
17
+ export interface ListQueryDialect {
18
+ /** 大小写不敏感的「包含」。 */
19
+ contains(_column: Column, _keyword: string): SQL;
20
+ /** 「这个 JSON 数组列里有没有元素含这段文字」。 */
21
+ jsonArrayContains(_column: Column, _keyword: string): SQL;
22
+ }
23
+ export interface ListQueryParams {
24
+ [field: string]: unknown;
25
+ orderBy?: string;
26
+ orderDir?: "asc" | "desc";
27
+ page?: number;
28
+ pageSize?: number;
29
+ }
30
+ export declare function createGetListQuery(dialect: ListQueryDialect): <TTable extends ListQueryTable, TSelection extends Record<string, unknown>>({ db, fields, jsonArrayFields, params, relations, scope, table, }: {
31
+ db: any;
32
+ fields: TSelection;
33
+ jsonArrayFields?: string[] | undefined;
34
+ /**
35
+ * 行级作用域。**必填**,不想隔离就显式传 NO_SCOPE —— 写成可选的话,漏传就退化成查全表,
36
+ * 而那是静默的越权(见 scope.ts)。它不走下面 params 那条筛选通道,因为那条的规矩是
37
+ * 「空值跳过」,一个取不到值的作用域会让整条 where 消失。
38
+ */
39
+ scope: ScopeArg;
40
+ params: ListQueryParams;
41
+ relations?: ListQueryRelation[] | undefined;
42
+ table: TTable;
43
+ }) => {
44
+ countQuery: any;
45
+ query: any;
46
+ };
@@ -0,0 +1,236 @@
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;
3
+ var _excluded = ["page", "pageSize", "orderBy", "orderDir"];
4
+ function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
5
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
6
+ 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."); }
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
+ 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
+ // ==============================================================================
24
+ // 列表查询的公共实现(pg / sqlite 共用)
25
+ // ==============================================================================
26
+ // 从前 pg 与 sqlite 各有一份 270 行的 get-list-query,逐字相同的部分占八成 —— 筛选条件怎么拼、
27
+ // 日期范围怎么认、多值怎么拆、排序与分页怎么加、计数查询怎么建,两边一模一样。**真正的方言
28
+ // 差异只有两条原语**:
29
+ //
30
+ // · 大小写不敏感的模糊匹配 —— pg 要 ilike,sqlite 的 like 本来就不区分大小写;
31
+ // · 「JSON 数组列里有没有含这段文字的元素」—— pg 用 jsonb_array_elements_text,
32
+ // sqlite 用 json_each(而且取值的字段名也不同:tag vs tag.value)。
33
+ //
34
+ // 所以这里收下一个 dialect 就够了,剩下的一份写完两边共用。与 route-operation 那边
35
+ // createXxxOperationFactory + 薄封装是同一个套路。
36
+ //
37
+ // 抄两份的代价不是抽象的:这个文件改过好几次(作用域先于筛选、空值跳过、日期范围),
38
+ // 每一次都得记得改另一棵树,而漏掉不会有任何东西报错 —— 只会让 sqlite 那边悄悄少一条规则。
39
+
40
+ import { and, asc, desc, eq, gte, inArray, lte, or, sql } from "drizzle-orm";
41
+ import { scopeCondition } from "../scope.js";
42
+
43
+ /**
44
+ * 核心用得到表的哪一部分:只有 `id`(计数与分组要它)和「按列名取列」。
45
+ * 两棵树的 BaseTable 都满足它,而 dialect 各自的 Table 类型不必进来。
46
+ */
47
+
48
+ /** 两套方言之间**全部**的差异。加第三种数据库时要写的也只有这两条。 */
49
+
50
+ // 按列名从表(或它的关联表)里取列。**唯一一处按字符串索引的地方** —— 收在这儿,
51
+ // 免得每个用到的地方都写一次断言。取不到回 undefined,调用方据此跳过这个条件。
52
+ function columnAt(table, key) {
53
+ return table[key];
54
+ }
55
+ export function createGetListQuery(dialect) {
56
+ return function getListQuery(_ref) {
57
+ var db = _ref.db,
58
+ fields = _ref.fields,
59
+ jsonArrayFields = _ref.jsonArrayFields,
60
+ params = _ref.params,
61
+ relations = _ref.relations,
62
+ scope = _ref.scope,
63
+ table = _ref.table;
64
+ var _params$page = params.page,
65
+ page = _params$page === void 0 ? 1 : _params$page,
66
+ _params$pageSize = params.pageSize,
67
+ pageSize = _params$pageSize === void 0 ? 10 : _params$pageSize,
68
+ _params$orderBy = params.orderBy,
69
+ orderBy = _params$orderBy === void 0 ? "createdAt" : _params$orderBy,
70
+ _params$orderDir = params.orderDir,
71
+ orderDir = _params$orderDir === void 0 ? "desc" : _params$orderDir,
72
+ filters = _objectWithoutProperties(params, _excluded);
73
+
74
+ // ==========================================================================
75
+ // 基础查询
76
+ // ==========================================================================
77
+ function buildBaseQuery() {
78
+ var queryFields = _objectSpread({}, fields);
79
+ if (relations !== null && relations !== void 0 && relations.length) {
80
+ var _iterator = _createForOfIteratorHelper(relations),
81
+ _step;
82
+ try {
83
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
84
+ var select = _step.value.select;
85
+ queryFields = _objectSpread(_objectSpread({}, queryFields), select);
86
+ }
87
+ } catch (err) {
88
+ _iterator.e(err);
89
+ } finally {
90
+ _iterator.f();
91
+ }
92
+ }
93
+ var query = db.select(queryFields).from(table);
94
+ if (relations !== null && relations !== void 0 && relations.length) {
95
+ query.groupBy.apply(query, [table.id].concat(_toConsumableArray(relations.filter(function (_ref2) {
96
+ var groupBy = _ref2.groupBy;
97
+ return groupBy;
98
+ }).filter(function (_ref3) {
99
+ var joined = _ref3.table;
100
+ return joined;
101
+ }).map(function (_ref4) {
102
+ var joined = _ref4.table;
103
+ return joined.id;
104
+ }))));
105
+ }
106
+ return query;
107
+ }
108
+
109
+ // 先在主表上找,找不到再去关联表上找。
110
+ function findTargetColumn(key) {
111
+ return [table].concat((relations === null || relations === void 0 ? void 0 : relations.filter(function (_ref5) {
112
+ var joined = _ref5.table;
113
+ return joined;
114
+ }).map(function (_ref6) {
115
+ var joined = _ref6.table;
116
+ return joined;
117
+ })) || []).map(function (candidate) {
118
+ return columnAt(candidate, key);
119
+ }).find(Boolean);
120
+ }
121
+
122
+ // ==========================================================================
123
+ // 单个筛选条件
124
+ // ==========================================================================
125
+ // 三条规矩,两套方言一致:
126
+ // · 名字里带 id 的按精确匹配(多值走 IN),其余按模糊;
127
+ // · 逗号分隔视为多值;
128
+ // · JSON 数组列走 dialect 那条 EXISTS。
129
+ function addCondition(conditions, key, value, targetColumn) {
130
+ var isIdField = /id/i.test(key);
131
+ var isJsonArray = jsonArrayFields === null || jsonArrayFields === void 0 ? void 0 : jsonArrayFields.includes(key);
132
+ if (typeof value !== "string") {
133
+ conditions.push(eq(targetColumn, value));
134
+ return;
135
+ }
136
+ if (value.includes(",")) {
137
+ var values = value.split(",").map(function (item) {
138
+ return item.trim();
139
+ }).filter(Boolean);
140
+ if (!values.length) {
141
+ return;
142
+ }
143
+ if (isJsonArray) {
144
+ // 多值时只认第一个 —— 与从前逐字一致,不趁重构改行为。
145
+ conditions.push(dialect.jsonArrayContains(targetColumn, values[0]));
146
+ } else if (isIdField) {
147
+ conditions.push(inArray(targetColumn, values));
148
+ } else {
149
+ conditions.push(or.apply(void 0, _toConsumableArray(values.map(function (item) {
150
+ return dialect.contains(targetColumn, item);
151
+ }))));
152
+ }
153
+ return;
154
+ }
155
+ if (isJsonArray) {
156
+ conditions.push(dialect.jsonArrayContains(targetColumn, value));
157
+ } else if (isIdField) {
158
+ conditions.push(eq(targetColumn, value));
159
+ } else {
160
+ conditions.push(dialect.contains(targetColumn, value));
161
+ }
162
+ }
163
+ function buildConditions() {
164
+ var conditions = [];
165
+ for (var _i = 0, _Object$entries = Object.entries(filters); _i < _Object$entries.length; _i++) {
166
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
167
+ key = _Object$entries$_i[0],
168
+ value = _Object$entries$_i[1];
169
+ // 空值跳过。**这条只对筛选成立**,作用域另走一条路(见下)。
170
+ if (!value) {
171
+ continue;
172
+ }
173
+
174
+ // 日期范围:xxxAtFrom / xxxAtTo 落到 xxxAt 那一列上。
175
+ if (key.endsWith("AtFrom") || key.endsWith("AtTo")) {
176
+ var baseFieldName = key.replace(/(AtFrom|AtTo)$/, "");
177
+ var _targetColumn = findTargetColumn("".concat(baseFieldName, "At"));
178
+ if (!_targetColumn) {
179
+ continue;
180
+ }
181
+ conditions.push(key.endsWith("AtFrom") ? gte(_targetColumn, new Date(value)) : lte(_targetColumn, new Date(value)));
182
+ continue;
183
+ }
184
+ var targetColumn = findTargetColumn(key);
185
+ if (!targetColumn) {
186
+ continue;
187
+ }
188
+ addCondition(conditions, key, value, targetColumn);
189
+ }
190
+ return conditions;
191
+ }
192
+ function buildOrderBy() {
193
+ var orderColumn = columnAt(table, orderBy);
194
+ return orderDir === "asc" ? asc(orderColumn) : desc(orderColumn);
195
+ }
196
+
197
+ // ==========================================================================
198
+ // 组装
199
+ // ==========================================================================
200
+ var baseQuery = buildBaseQuery();
201
+
202
+ // **作用域先于筛选加进去**,且它不受 buildConditions 里「空值跳过」那条规矩管:
203
+ // 那条规矩对 `?name=` 这种空参数是对的,对归属则是灾难性的 —— 条件消失即全表可见。
204
+ var scopeSql = scopeCondition(table, scope);
205
+ var conditions = scopeSql ? [scopeSql] : [];
206
+ conditions.push.apply(conditions, _toConsumableArray(buildConditions()));
207
+ var where = conditions.length > 0 ? and.apply(void 0, conditions) : undefined;
208
+ var query = baseQuery.where(where).orderBy(buildOrderBy()).limit(pageSize).offset((page - 1) * pageSize);
209
+ var countQuery = db.select({
210
+ count: sql(_templateObject || (_templateObject = _taggedTemplateLiteral(["COUNT(DISTINCT ", ")"])), table.id)
211
+ }).from(table).where(where);
212
+ if (relations !== null && relations !== void 0 && relations.length) {
213
+ var _iterator2 = _createForOfIteratorHelper(relations),
214
+ _step2;
215
+ try {
216
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
217
+ var _step2$value = _step2.value,
218
+ relationTable = _step2$value.table,
219
+ joinSql = _step2$value.sql;
220
+ if (relationTable) {
221
+ query.leftJoin(relationTable, joinSql);
222
+ countQuery.leftJoin(relationTable, joinSql);
223
+ }
224
+ }
225
+ } catch (err) {
226
+ _iterator2.e(err);
227
+ } finally {
228
+ _iterator2.f();
229
+ }
230
+ }
231
+ return {
232
+ countQuery: countQuery,
233
+ query: query
234
+ };
235
+ };
236
+ }
@@ -1,34 +1,21 @@
1
1
  import { BaseTable, GetListRelations } from "../types.js";
2
2
  import { SelectedFields } from "drizzle-orm/pg-core/query-builders/select.types";
3
- import { SQL } from "drizzle-orm";
4
3
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
5
4
  import { ScopeArg } from "../scope.js";
6
- export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>({ db, fields, jsonArrayFields, params, relations, scope, table, }: {
5
+ import { type ListQueryParams } from "./get-list-query-core.js";
6
+ export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>(args: {
7
7
  db: NodePgDatabase<Record<string, unknown>>;
8
8
  fields: TSelection;
9
9
  jsonArrayFields?: string[];
10
10
  /**
11
11
  * 行级作用域。**必填**,不想隔离就显式传 NO_SCOPE —— 写成可选的话,漏传就退化成查全表,
12
- * 而那是静默的越权(见 scope.ts)。它不走下面 params 那条筛选通道,因为那条的规矩是
13
- * 「空值跳过」,一个取不到值的作用域会让整条 where 消失。
12
+ * 而那是静默的越权(见 scope.ts)。
14
13
  */
15
14
  scope: ScopeArg;
16
- params: {
17
- [field: string]: unknown;
18
- orderBy?: keyof BaseTable;
19
- orderDir?: "asc" | "desc";
20
- page?: number;
21
- pageSize?: number;
22
- };
15
+ params: ListQueryParams;
23
16
  relations?: GetListRelations;
24
17
  table: TTable;
25
18
  }): {
26
- countQuery: Omit<import("drizzle-orm/pg-core").PgSelectBase<string, {
27
- count: SQL<unknown>;
28
- }, "partial", Record<string, "not-null">, false, "where", {
29
- count: unknown;
30
- }[], {
31
- count: import("drizzle-orm").DrizzleTypeError<"You cannot reference this field without assigning it an alias first - use `.as(<alias>)`">;
32
- }>, "where">;
19
+ countQuery: any;
33
20
  query: any;
34
21
  };