@technicity/data-service-generator 0.14.5 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import type { IDialect, ISupplementClientOpts } from "../runtime/IRuntime";
2
- declare type ISpecialCaseUuidColumn = boolean;
3
- declare type IIncludeMappedFields = boolean;
4
- declare type IGenerateInput = {
2
+ type ISpecialCaseUuidColumn = boolean;
3
+ type IIncludeMappedFields = boolean;
4
+ type IGenerateInput = {
5
5
  dialect: IDialect;
6
6
  database: string;
7
7
  user: string;
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.generate = void 0;
29
+ exports.generate = generate;
30
30
  const path = __importStar(require("node:path"));
31
31
  const fs = __importStar(require("node:fs"));
32
32
  const os = __importStar(require("node:os"));
@@ -43,6 +43,7 @@ const json_schema_to_typescript_1 = require("json-schema-to-typescript");
43
43
  const getDuplicates_1 = require("../lib/getDuplicates");
44
44
  const isNotNullOrUndefined_1 = require("../lib/isNotNullOrUndefined");
45
45
  const MySQL_1 = require("../runtime/lib/MySQL");
46
+ const capitalizeFirstLetter_1 = require("../lib/capitalizeFirstLetter");
46
47
  // json-schema-to-typescript inlines everything. We don't want that,
47
48
  // so use `tsType`, and add imports manually.
48
49
  // https://github.com/bcherny/json-schema-to-typescript#custom-schema-properties
@@ -201,7 +202,6 @@ async function generate(input) {
201
202
  fse.copySync(tmpBuildOutputPath, sdkOutputPath);
202
203
  fse.removeSync(tmpDirPath);
203
204
  }
204
- exports.generate = generate;
205
205
  function init(input) {
206
206
  const { database, user, password, host, port, server } = input;
207
207
  if (dialect === "mysql") {
@@ -256,13 +256,18 @@ async function getSDKSource(input, specialCaseUuidColumn, supplementClientOpts,
256
256
  .concat(Array.from(set).sort())
257
257
  .join(",\n")} } from "./types";`;
258
258
  }
259
- const src = `import type { IRuntime, TMiddleware, TContext } from "./IRuntime"
259
+ const src = `import { AsyncLocalStorage } from "node:async_hooks";
260
+ import type { IRuntime, TMiddleware, TContext, TOnHandler, EventOnHandlerError } from "./IRuntime"
260
261
  import { artifacts } from "./artifacts";
261
262
 
262
263
  ${getTypeImports()}
263
264
 
265
+ const asyncLocalStorage = new AsyncLocalStorage<{ isInOnHandler: boolean }>();
266
+
264
267
  export class SDK {
265
268
  runtime: IRuntime;
269
+ onHandlerMap: Map<string, TOnHandler>;
270
+ eventTarget: EventTarget;
266
271
 
267
272
  constructor(opts: {
268
273
  runtime: any;
@@ -276,6 +281,8 @@ async function getSDKSource(input, specialCaseUuidColumn, supplementClientOpts,
276
281
  this.runtime = new opts.runtime(opts.clientOpts, ${supplementClientOpts === true
277
282
  ? "{ supplementClientOpts: true, ...otherOpts }"
278
283
  : "otherOpts"}, artifacts);
284
+ this.onHandlerMap = new Map();
285
+ this.eventTarget = new EventTarget();
279
286
  }
280
287
 
281
288
  $use(middleware: TMiddleware) {
@@ -310,6 +317,8 @@ async function getSDKSource(input, specialCaseUuidColumn, supplementClientOpts,
310
317
  }) {
311
318
  const { dbCall, commit, rollback } = await this.runtime.$startTransaction(input);
312
319
  const runtime = this.runtime;
320
+ const eventTarget = this.eventTarget;
321
+ const onHandlerMap = this.onHandlerMap;
313
322
  return {
314
323
  $commit: commit,
315
324
  $rollback: rollback,
@@ -345,6 +354,10 @@ async function getSDKSource(input, specialCaseUuidColumn, supplementClientOpts,
345
354
  }
346
355
  }
347
356
 
357
+ onOnHandlerError(cb: (event: EventOnHandlerError<unknown>) => void) {
358
+ this.eventTarget.addEventListener("error", cb);
359
+ }
360
+
348
361
  ${(await Promise.all(input.flatMap(async (x) => {
349
362
  if (x.kind === "getOne") {
350
363
  const findOnes = await getFindOnes(x, specialCaseUuidColumn);
@@ -374,6 +387,15 @@ async function getSDKSource(input, specialCaseUuidColumn, supplementClientOpts,
374
387
  return getMethodSourceDeleteList(x, false);
375
388
  }
376
389
  }))).join("\n\n")}
390
+
391
+ ${(await Promise.all(input.flatMap(async (x) => {
392
+ if (x.kind === "patchOne") {
393
+ const findOnes = await getFindOnes(x, specialCaseUuidColumn);
394
+ return getMethodSourceOnHandlerPatchOne(x, findOnes);
395
+ }
396
+ })))
397
+ .filter(Boolean)
398
+ .join("\n\n")}
377
399
  }
378
400
 
379
401
  ${await Promise.all(Object.entries(artifacts).map(async ([table, tableArtifacts]) => {
@@ -490,6 +512,7 @@ function getMethodSourceGetOne(x, findOnes, isTransaction) {
490
512
  artifacts,
491
513
  context: param2?.context,
492
514
  skipCache: param2?.skipCache,
515
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
493
516
  ${isTransaction ? "dbCall" : ""}
494
517
  }
495
518
  );
@@ -510,6 +533,7 @@ function getMethodSourceGetList(x, isTransaction) {
510
533
  artifacts,
511
534
  context: param2?.context,
512
535
  skipCache: param2?.skipCache,
536
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
513
537
  ${isTransaction ? "dbCall" : ""}
514
538
  }
515
539
  );
@@ -530,6 +554,7 @@ function getMethodSourceGetListPaginated(x, isTransaction) {
530
554
  artifacts,
531
555
  context: param2?.context,
532
556
  skipCache: param2?.skipCache,
557
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
533
558
  ${isTransaction ? "dbCall" : ""}
534
559
  }
535
560
  );
@@ -548,6 +573,10 @@ function getMethodSourcePostOne(x, specialCaseUuidColumn, isTransaction) {
548
573
  artifacts,
549
574
  fields: param2?.$fields as any,
550
575
  context: {...param2?.context, specialCaseUuidColumn: ${JSON.stringify(specialCaseUuidColumn)}},
576
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
577
+ onHandler: ${isTransaction ? "onHandlerMap" : "this.onHandlerMap"}.get("${mapKindToAction(x.kind)}-${x.table}"),
578
+ asyncLocalStorage,
579
+ sdk: this,
551
580
  ${isTransaction ? "dbCall" : ""}
552
581
  });
553
582
  }`;
@@ -569,10 +598,25 @@ return ${isTransaction ? "runtime" : "this.runtime"}.resolve({
569
598
  artifacts,
570
599
  fields: param2?.$fields as any,
571
600
  context: param2?.context,
601
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
602
+ onHandler: ${isTransaction ? "onHandlerMap" : "this.onHandlerMap"}.get("${mapKindToAction(x.kind)}-${x.table}"),
603
+ asyncLocalStorage,
604
+ sdk: this,
572
605
  ${isTransaction ? "dbCall" : ""}
573
606
  });
574
607
  }`;
575
608
  }
609
+ function getMethodSourceOnHandlerPatchOne(x, findOnes) {
610
+ return `on${(0, capitalizeFirstLetter_1.capitalizeFirstLetter)(x.methodName)}(handler:
611
+ (sdk: InstanceType<typeof SDK>, input: { $where: ${findOnes
612
+ .map((findOne) => `{ ${findOne.name}: ${findOne.type}${findOne.nullable ? " | null" : ""} }`)
613
+ .join(" | ")}, data: ${x.typeDataName} },
614
+ output: Partial<${getTypeReturnName(x.table)}>
615
+ ) => Promise<void>
616
+ ): void {
617
+ this.onHandlerMap.set("${mapKindToAction(x.kind)}-${x.table}", handler);
618
+ }`;
619
+ }
576
620
  function getMethodSourcePatchList(x, isTransaction) {
577
621
  const param2 = `{ ${keyFields}?: ${x.typeFieldsName}, correlationId?: string, context?: TContext }`;
578
622
  return `async ${x.methodName}<T extends ${param2}>(
@@ -588,6 +632,10 @@ function getMethodSourcePatchList(x, isTransaction) {
588
632
  artifacts,
589
633
  fields: param2?.$fields as any,
590
634
  context: param2?.context,
635
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
636
+ onHandler: ${isTransaction ? "onHandlerMap" : "this.onHandlerMap"}.get("${mapKindToAction(x.kind)}-${x.table}"),
637
+ asyncLocalStorage,
638
+ sdk: this,
591
639
  ${isTransaction ? "dbCall" : ""}
592
640
  });
593
641
  }`;
@@ -605,6 +653,10 @@ function getMethodSourceDeleteOne(x, findOnes, isTransaction) {
605
653
  args: { $where: param1 },
606
654
  artifacts,
607
655
  context: param2?.context,
656
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
657
+ onHandler: ${isTransaction ? "onHandlerMap" : "this.onHandlerMap"}.get("${mapKindToAction(x.kind)}-${x.table}"),
658
+ asyncLocalStorage,
659
+ sdk: this,
608
660
  ${isTransaction ? "dbCall" : ""}
609
661
  });
610
662
  }`;
@@ -620,6 +672,10 @@ function getMethodSourceDeleteList(x, isTransaction) {
620
672
  args: param1,
621
673
  artifacts,
622
674
  context: param2?.context,
675
+ eventTarget: ${isTransaction ? "eventTarget" : "this.eventTarget"},
676
+ onHandler: ${isTransaction ? "onHandlerMap" : "this.onHandlerMap"}.get("${mapKindToAction(x.kind)}-${x.table}"),
677
+ asyncLocalStorage,
678
+ sdk: this,
623
679
  ${isTransaction ? "dbCall" : ""}
624
680
  });
625
681
  }`;
@@ -0,0 +1 @@
1
+ export declare function capitalizeFirstLetter(str: string): string;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.capitalizeFirstLetter = capitalizeFirstLetter;
4
+ function capitalizeFirstLetter(str) {
5
+ return str.charAt(0).toUpperCase() + str.slice(1);
6
+ }
@@ -1,10 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDuplicates = void 0;
3
+ exports.getDuplicates = getDuplicates;
4
4
  function getDuplicates(arr) {
5
5
  return arr.reduce((agg, col) => {
6
6
  agg.filter[col] = agg.filter[col] ? agg.dup.push(col) : 2;
7
7
  return agg;
8
8
  }, { filter: {}, dup: [] }).dup;
9
9
  }
10
- exports.getDuplicates = getDuplicates;
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isNotNullOrUndefined = void 0;
3
+ exports.isNotNullOrUndefined = isNotNullOrUndefined;
4
4
  // https://github.com/Microsoft/TypeScript/issues/16069
5
5
  function isNotNullOrUndefined(input) {
6
6
  return input != null;
7
7
  }
8
- exports.isNotNullOrUndefined = isNotNullOrUndefined;
@@ -1,7 +1,7 @@
1
1
  import Redis, { Cluster } from "ioredis";
2
2
  import { TResolveParams } from "./IRuntime";
3
3
  import Stats from "./Stats";
4
- export declare type RedisConfig = {
4
+ export type RedisConfig = {
5
5
  host: string;
6
6
  port: number;
7
7
  tls?: boolean;
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  export interface IRuntime {
2
3
  resolve(input: TResolveParams): Promise<any>;
3
4
  $queryRaw(sql: string, values?: any[]): Promise<any>;
@@ -9,8 +10,8 @@ export interface IRuntime {
9
10
  isolationLevel?: "READ UNCOMMITTED" | "READ COMMITTED" | "REPEATABLE READ" | "SERIALIZABLE";
10
11
  }): Promise<TBeginTransactionResult>;
11
12
  }
12
- export declare type TAction = "findUnique" | "findMany" | "findManyPaginated" | "create" | "update" | "updateMany" | "delete" | "deleteMany";
13
- export declare type TResolveParams = {
13
+ export type TAction = "findUnique" | "findMany" | "findManyPaginated" | "create" | "update" | "updateMany" | "delete" | "deleteMany";
14
+ export type TResolveParams = {
14
15
  resource: string;
15
16
  action: TAction;
16
17
  args?: IArgs;
@@ -20,54 +21,68 @@ export declare type TResolveParams = {
20
21
  context?: TContext;
21
22
  skipCache?: boolean;
22
23
  dbCall?: TDbCall;
23
- };
24
- export declare type TContext = {
24
+ eventTarget: EventTarget;
25
+ onHandler?: TOnHandler;
26
+ asyncLocalStorage?: AsyncLocalStorage<{
27
+ isInOnHandler?: boolean;
28
+ isTransaction?: boolean;
29
+ }>;
30
+ sdk?: unknown;
31
+ };
32
+ export type TOnHandler = (sdk: unknown, input: unknown, output: unknown) => Promise<void>;
33
+ export declare class EventOnHandlerError<T> extends Event {
34
+ error: T;
35
+ constructor(message: string, data: ConstructorParameters<typeof Event>[1] & {
36
+ error: T;
37
+ });
38
+ }
39
+ export type TContext = {
25
40
  [k: string]: any;
26
41
  };
27
- export declare type TMiddleware = (params: TResolveParams, next: (params: TResolveParams) => Promise<any>) => Promise<any>;
28
- export declare type IDialect = "mysql" | "mssql" | "sqlite";
29
- export declare type TDbCall = (q: string) => Promise<any>;
30
- export declare type TFormatQuery = (q: string, values: any[]) => string;
31
- export declare type TBeginTransaction = () => Promise<TBeginTransactionResult>;
32
- declare type TBeginTransactionResult = {
42
+ export type TMiddleware = (params: TResolveParams, next: (params: TResolveParams) => Promise<any>) => Promise<any>;
43
+ export type IDialect = "mysql" | "mssql" | "sqlite";
44
+ export type TDbCall = (q: string) => Promise<any>;
45
+ export type TFormatQuery = (q: string, values: any[]) => string;
46
+ export type TBeginTransaction = () => Promise<TBeginTransactionResult>;
47
+ type TBeginTransactionResult = {
33
48
  dbCall: (q: string) => Promise<any>;
34
49
  commit: () => Promise<void>;
35
50
  rollback: () => Promise<void>;
36
51
  };
37
- export declare type ISupplementClientOpts = boolean;
38
- export declare type IOrderBy = {
52
+ export type ISupplementClientOpts = boolean;
53
+ export type IOrderBy = {
39
54
  column: string;
40
55
  direction: any;
41
56
  }[];
42
- export declare type IArgs = {
57
+ export type IArgs = {
43
58
  [k: string]: any;
44
59
  };
45
- export declare type TSelect = {
60
+ export type TSelect = {
46
61
  [k: string]: boolean | {
47
62
  $fields?: TSelect;
48
63
  };
49
64
  };
50
- declare type IWhere = (table: string, args: IArgs) => string | undefined;
51
- declare type IASTChildColumn = {
65
+ type IWhere = (table: string, args: IArgs) => string | undefined;
66
+ type IASTChildColumn = {
52
67
  type: "column";
53
68
  name: string;
54
69
  fieldName: string;
55
70
  as: string;
56
71
  fromOtherTable?: string;
57
72
  };
58
- declare type IASTChildComposite = {
73
+ type IASTChildComposite = {
59
74
  type: "composite";
60
75
  name: string[];
61
76
  fieldName: string;
62
77
  as: string;
63
78
  fromOtherTable?: string;
64
79
  };
65
- declare type ISqlJoin = (t1: string, t2: string, args: IArgs) => string;
66
- declare type ISqlBatch = {
80
+ type ISqlJoin = (t1: string, t2: string, args: IArgs) => string;
81
+ type ISqlBatch = {
67
82
  thisKey: IASTChildColumn;
68
83
  parentKey: IASTChildColumn;
69
84
  };
70
- declare type IJunction = {
85
+ type IJunction = {
71
86
  sqlTable: string;
72
87
  as: string;
73
88
  uniqueKey: string | string[];
@@ -83,7 +98,7 @@ declare type IJunction = {
83
98
  where?: IWhere;
84
99
  sqlJoins: ISqlJoin[];
85
100
  };
86
- export declare type IGetSQLASTInput = {
101
+ export type IGetSQLASTInput = {
87
102
  table: string;
88
103
  fieldName: string;
89
104
  fields: TSelect;
@@ -100,17 +115,17 @@ export declare type IGetSQLASTInput = {
100
115
  dialect: IDialect;
101
116
  firstChild?: IASTChildColumn | IASTChildComposite;
102
117
  };
103
- export declare type IRelation = {
118
+ export type IRelation = {
104
119
  table: string;
105
120
  foreignKey: string;
106
121
  referencedTable: string;
107
122
  referencedKey: string;
108
123
  nullable: boolean;
109
124
  };
110
- declare type IOneToManyOrManyToOne = "one-to-many__many-to-one";
111
- declare type IManyToMany = "many-to-many";
112
- declare type IRelationKind = "one-to-many" | "many-to-one";
113
- export declare type IRelationOneToManyOrManyToOne = {
125
+ type IOneToManyOrManyToOne = "one-to-many__many-to-one";
126
+ type IManyToMany = "many-to-many";
127
+ type IRelationKind = "one-to-many" | "many-to-one";
128
+ export type IRelationOneToManyOrManyToOne = {
114
129
  type: IOneToManyOrManyToOne;
115
130
  kind: IRelationKind;
116
131
  grabMany: boolean;
@@ -119,7 +134,7 @@ export declare type IRelationOneToManyOrManyToOne = {
119
134
  relation: IRelation;
120
135
  nullable: boolean;
121
136
  };
122
- export declare type IRelationManyToMany = {
137
+ export type IRelationManyToMany = {
123
138
  type: IManyToMany;
124
139
  grabMany: boolean;
125
140
  table: string;
@@ -127,8 +142,8 @@ export declare type IRelationManyToMany = {
127
142
  name: string;
128
143
  relations: IRelation[];
129
144
  };
130
- export declare type IRelationField = IRelationOneToManyOrManyToOne | IRelationManyToMany;
131
- export declare type IMappedField = {
145
+ export type IRelationField = IRelationOneToManyOrManyToOne | IRelationManyToMany;
146
+ export type IMappedField = {
132
147
  name: string;
133
148
  as: string;
134
149
  type: string;
@@ -138,7 +153,7 @@ export declare type IMappedField = {
138
153
  referencedTable: string;
139
154
  referencedKey: string;
140
155
  };
141
- export declare type IArtifacts = {
156
+ export type IArtifacts = {
142
157
  [k: string]: {
143
158
  table: string;
144
159
  primaryKey: string;
@@ -164,8 +179,8 @@ export declare type IArtifacts = {
164
179
  } | null;
165
180
  };
166
181
  };
167
- export declare type TFieldType = "string" | "boolean" | "number" | "integer";
168
- export declare type TField = {
182
+ export type TFieldType = "string" | "boolean" | "number" | "integer";
183
+ export type TField = {
169
184
  kind: "scalar";
170
185
  type: TFieldType;
171
186
  name: string;
@@ -1,2 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventOnHandlerError = void 0;
4
+ class EventOnHandlerError extends Event {
5
+ constructor(message, data) {
6
+ super(message, data);
7
+ this.error = data.error;
8
+ }
9
+ }
10
+ exports.EventOnHandlerError = EventOnHandlerError;
@@ -1,7 +1,7 @@
1
1
  import Database from "better-sqlite3";
2
2
  import type { IRuntime, TMiddleware, TResolveParams, IArtifacts, ISupplementClientOpts } from "./IRuntime";
3
3
  import { MiddlewareHandler } from "./lib/shared";
4
- declare type TClientOpts = {
4
+ type TClientOpts = {
5
5
  filename: string;
6
6
  } & Parameters<typeof Database>[1];
7
7
  export declare class RuntimeSQLite implements IRuntime {
@@ -128,7 +128,12 @@ class RuntimeSQLite {
128
128
  }
129
129
  }
130
130
  async rollback() {
131
- __classPrivateFieldGet(this, _RuntimeSQLite_db, "f").prepare("ROLLBACK").run();
131
+ try {
132
+ __classPrivateFieldGet(this, _RuntimeSQLite_db, "f").prepare("ROLLBACK").run();
133
+ }
134
+ catch (e) {
135
+ console.log(e);
136
+ }
132
137
  }
133
138
  }
134
139
  exports.RuntimeSQLite = RuntimeSQLite;
@@ -4,9 +4,5 @@ declare class Stats {
4
4
  constructor(client: Redis | Cluster);
5
5
  updateStats: (ms: number, category: string) => Promise<void>;
6
6
  }
7
- declare namespace timer {
8
- type Callback = (time: number, ...params: any[]) => void;
9
- type Params<T> = T extends (ms: number, ...params: infer U) => any ? U : never;
10
- }
11
7
  export declare function timer(): <T extends timer.Callback>(callback: T, ...args: timer.Params<T>) => void;
12
8
  export default Stats;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.timer = void 0;
3
+ exports.timer = timer;
4
4
  const perf_hooks_1 = require("perf_hooks");
5
5
  class Stats {
6
6
  constructor(client) {
@@ -28,5 +28,4 @@ function timer() {
28
28
  callback(perf_hooks_1.performance.now() - start, ...args);
29
29
  };
30
30
  }
31
- exports.timer = timer;
32
31
  exports.default = Stats;
@@ -2,7 +2,7 @@
2
2
  // If a many-to-one relation's ID field is null, we want the
3
3
  // relation field to be null as well, not undefined.
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.addNullFallbacks = void 0;
5
+ exports.addNullFallbacks = addNullFallbacks;
6
6
  function addNullFallbacks(sqlAST, data) {
7
7
  if (data == null) {
8
8
  return;
@@ -30,4 +30,3 @@ function addNullFallbacks(sqlAST, data) {
30
30
  }
31
31
  }
32
32
  }
33
- exports.addNullFallbacks = addNullFallbacks;
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decodeCursor = exports.encodeCursor = void 0;
3
+ exports.encodeCursor = encodeCursor;
4
+ exports.decodeCursor = decodeCursor;
4
5
  function encodeCursor(cursor) {
5
6
  return Buffer.from(JSON.stringify(cursor)).toString("base64");
6
7
  }
7
- exports.encodeCursor = encodeCursor;
8
8
  function decodeCursor(cursor) {
9
9
  return JSON.parse(Buffer.from(cursor, "base64").toString("utf8"));
10
10
  }
11
- exports.decodeCursor = decodeCursor;
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDateTimeStringMySQL = void 0;
3
+ exports.getDateTimeStringMySQL = getDateTimeStringMySQL;
4
4
  // Assumes input uses zero offset
5
5
  function getDateTimeStringMySQL(dateTimeString) {
6
6
  return dateTimeString.replace("T", " ").slice(0, 19);
7
7
  }
8
- exports.getDateTimeStringMySQL = getDateTimeStringMySQL;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getOrderBy = void 0;
3
+ exports.getOrderBy = getOrderBy;
4
4
  // https://gist.github.com/pcattori/2bb645d587e45c9fdbcabf5cef7a7106
5
5
  function getOrderBy(args, primaryKey) {
6
6
  let out = undefined;
@@ -41,7 +41,6 @@ function getOrderBy(args, primaryKey) {
41
41
  }
42
42
  return { orderBy: out, flip };
43
43
  }
44
- exports.getOrderBy = getOrderBy;
45
44
  function getFlip(args) {
46
45
  return args?.$paginate?.last != null;
47
46
  }
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getSqlAst = void 0;
29
+ exports.getSqlAst = getSqlAst;
30
30
  const SqlString = __importStar(require("sqlstring"));
31
31
  // @ts-ignore
32
32
  const TSqlString = __importStar(require("tsqlstring"));
@@ -220,7 +220,6 @@ function getSqlAst(input) {
220
220
  }))
221
221
  };
222
222
  }
223
- exports.getSqlAst = getSqlAst;
224
223
  function keyToASTChild(key, namespace, fromOtherTable) {
225
224
  if (Array.isArray(key)) {
226
225
  const clumsyName = toClumsyName(key);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getWhere = void 0;
3
+ exports.getWhere = getWhere;
4
4
  const stringifyWhere_1 = require("./stringifyWhere");
5
5
  function getWhere(
6
6
  // Note: `table` is not escaped in getWhere, so it should be escaped beforehand.
@@ -18,4 +18,3 @@ table, args, dialect, orderBy, rowWithMatchingCursor) {
18
18
  rowWithMatchingCursor,
19
19
  }) || null);
20
20
  }
21
- exports.getWhere = getWhere;
@@ -1,4 +1,4 @@
1
- import type { IGetSQLASTInput, IArtifacts, IDialect, TDbCall, TFormatQuery, TBeginTransaction, TContext, TMiddleware, TResolveParams } from "../IRuntime";
1
+ import { type IGetSQLASTInput, type IArtifacts, type IDialect, type TDbCall, type TFormatQuery, type TBeginTransaction, type TContext, type TMiddleware, type TResolveParams } from "../IRuntime";
2
2
  import Cache from "../Cache";
3
3
  export declare function resolve(input: TResolveParams, dbCall: TDbCall, formatQuery: TFormatQuery, beginTransaction: TBeginTransaction, dialect: IDialect, middlewareHandler: MiddlewareHandler<TMiddleware>, context: TContext, cache?: Cache): Promise<any>;
4
4
  export declare class MiddlewareHandler<M extends Function> {
@@ -26,7 +26,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports._prepareWhere = exports.whereNeedsProcessing = exports.postProcess = exports.MiddlewareHandler = exports.resolve = void 0;
29
+ exports.MiddlewareHandler = void 0;
30
+ exports.resolve = resolve;
31
+ exports.postProcess = postProcess;
32
+ exports.whereNeedsProcessing = whereNeedsProcessing;
33
+ exports._prepareWhere = _prepareWhere;
30
34
  // @ts-ignore
31
35
  // import * as queryAST from "join-monster/dist/query-ast-to-sql-ast";
32
36
  // @ts-ignore
@@ -39,6 +43,7 @@ const async_hooks_1 = require("async_hooks");
39
43
  const _ = __importStar(require("lodash/fp"));
40
44
  const uuid_1 = require("uuid");
41
45
  const getSqlAst_1 = require("./getSqlAst");
46
+ const IRuntime_1 = require("../IRuntime");
42
47
  const getWhere_1 = require("./getWhere");
43
48
  const getDateTimeStringMySQL_1 = require("./getDateTimeStringMySQL");
44
49
  const cursor_1 = require("./cursor");
@@ -60,13 +65,40 @@ async function resolve(input, dbCall, formatQuery, beginTransaction, dialect, mi
60
65
  return nextMiddleware(paramsMaybeMutated, consumer);
61
66
  }
62
67
  const paramsChanged = { ...input, ...params };
63
- return _resolve(paramsChanged, dbCall, formatQuery, beginTransaction, dialect, context, cache);
68
+ const p = _resolve(paramsChanged, dbCall, formatQuery, beginTransaction, dialect, context, cache);
69
+ const onHandler = input.onHandler;
70
+ const asyncLocalStorage = input.asyncLocalStorage;
71
+ if (typeof onHandler === "function" &&
72
+ asyncLocalStorage != null &&
73
+ asyncLocalStorage?.getStore()?.isInOnHandler !== true) {
74
+ return p.then((output) => asyncLocalStorage
75
+ .run({ isInOnHandler: true }, async () => onHandler(input.sdk, { ...input.args, data: input.data }, output))
76
+ .then(() => output)
77
+ .catch((error) => {
78
+ input.eventTarget.dispatchEvent(new IRuntime_1.EventOnHandlerError("error", { error }));
79
+ return output;
80
+ }));
81
+ }
82
+ return p;
64
83
  };
65
84
  return resource.runInAsyncScope(() => consumer(params));
66
85
  }
67
- return _resolve(input, dbCall, formatQuery, beginTransaction, dialect, context, cache);
86
+ const p = _resolve(input, dbCall, formatQuery, beginTransaction, dialect, context, cache);
87
+ const onHandler = input.onHandler;
88
+ const asyncLocalStorage = input.asyncLocalStorage;
89
+ if (typeof onHandler === "function" &&
90
+ asyncLocalStorage != null &&
91
+ asyncLocalStorage?.getStore()?.isInOnHandler !== true) {
92
+ return p.then((output) => asyncLocalStorage
93
+ .run({ isInOnHandler: true }, async () => onHandler(input.sdk, { ...input.args, data: input.data }, output))
94
+ .then(() => output)
95
+ .catch((error) => {
96
+ input.eventTarget.dispatchEvent(new IRuntime_1.EventOnHandlerError("error", { error }));
97
+ return output;
98
+ }));
99
+ }
100
+ return p;
68
101
  }
69
- exports.resolve = resolve;
70
102
  function _resolve(input, dbCall, formatQuery, beginTransaction, dialect, context, cache) {
71
103
  switch (input.action) {
72
104
  case "findMany":
@@ -842,7 +874,6 @@ function postProcess(data, fields, shouldRemoveExtraKeys) {
842
874
  removeExtraKeys(data, fields);
843
875
  }
844
876
  }
845
- exports.postProcess = postProcess;
846
877
  function removeExtraKeys(data, fields) {
847
878
  if (data == null || (Array.isArray(data) && data[0] == null)) {
848
879
  return;
@@ -938,7 +969,6 @@ function typeCastSqlite(data, fields, table, artifacts) {
938
969
  function whereNeedsProcessing(where) {
939
970
  return JSON.stringify(where).includes("Uuid");
940
971
  }
941
- exports.whereNeedsProcessing = whereNeedsProcessing;
942
972
  async function _prepareWhere(artifacts, table, data, dbCall, formatQuery) {
943
973
  const mappedFields = artifacts[table].mappedFields;
944
974
  let out = {};
@@ -1034,7 +1064,6 @@ async function _prepareWhere(artifacts, table, data, dbCall, formatQuery) {
1034
1064
  });
1035
1065
  return out;
1036
1066
  }
1037
- exports._prepareWhere = _prepareWhere;
1038
1067
  function getPrepareWhereNotFoundMessage(mappedField, value) {
1039
1068
  return `Not found: unable to map \`${mappedField.referencedTable}\`.\`${mappedField.name}\` to \`${mappedField.referencedTable}\`.\`${mappedField.referencedKey}\` for the value \`${value}\`.`;
1040
1069
  }
@@ -1,8 +1,8 @@
1
1
  import type { IOrderBy, IDialect } from "../IRuntime";
2
- declare type IWhere = {
2
+ type IWhere = {
3
3
  [k: string]: any;
4
4
  };
5
- declare type IArgs = {
5
+ type IArgs = {
6
6
  [k: string]: any;
7
7
  };
8
8
  export declare function stringifyWhere(input: {
@@ -23,7 +23,9 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getEscape = exports.getEscapeId = exports.stringifyWhere = void 0;
26
+ exports.stringifyWhere = stringifyWhere;
27
+ exports.getEscapeId = getEscapeId;
28
+ exports.getEscape = getEscape;
27
29
  const _ = __importStar(require("lodash/fp"));
28
30
  const MySqlString = __importStar(require("sqlstring"));
29
31
  // @ts-expect-error
@@ -49,7 +51,6 @@ function stringifyWhere(input) {
49
51
  }
50
52
  return result;
51
53
  }
52
- exports.stringifyWhere = stringifyWhere;
53
54
  function _stringifyWhere(where, table, escapeId, escape, result) {
54
55
  if (Object.prototype.hasOwnProperty.call(where, "$and")) {
55
56
  if (Object.keys(where).length !== 1) {
@@ -239,7 +240,6 @@ function getEscapeId(dialect) {
239
240
  }
240
241
  throw new Error("Unsupported dialect: " + dialect);
241
242
  }
242
- exports.getEscapeId = getEscapeId;
243
243
  function getEscape(dialect) {
244
244
  if (dialect === "mysql") {
245
245
  return MySqlString.escape.bind(MySqlString);
@@ -252,4 +252,3 @@ function getEscape(dialect) {
252
252
  }
253
253
  throw new Error("Unsupported dialect: " + dialect);
254
254
  }
255
- exports.getEscape = getEscape;
@@ -1,3 +1,3 @@
1
- declare type TValueCast = (value: any) => any;
1
+ type TValueCast = (value: any) => any;
2
2
  export declare function typeCastMSSQL(customTypeCast?: (meta: any, mssql: any) => TValueCast): (result: any, meta: any) => any;
3
3
  export {};
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.typeCastMSSQL = void 0;
26
+ exports.typeCastMSSQL = typeCastMSSQL;
27
27
  const mssql = __importStar(require("mssql"));
28
28
  // TODO: see https://github.com/tediousjs/node-mssql/pull/1171
29
29
  function typeCastMSSQL(customTypeCast) {
@@ -60,4 +60,3 @@ function typeCastMSSQL(customTypeCast) {
60
60
  });
61
61
  };
62
62
  }
63
- exports.typeCastMSSQL = typeCastMSSQL;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.flatten = exports.mapAsync = void 0;
3
+ exports.mapAsync = mapAsync;
4
+ exports.flatten = flatten;
4
5
  /**
5
6
  * Eagerly resolve and map input values then concatinate.
6
7
  */
@@ -8,8 +9,6 @@ async function mapAsync(source, mapFunction) {
8
9
  const output = (await source).map(mapFunction);
9
10
  return Promise.all(flatten(output)).then(flatten);
10
11
  }
11
- exports.mapAsync = mapAsync;
12
12
  function flatten(array) {
13
13
  return [].concat(...array);
14
14
  }
15
- exports.flatten = flatten;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.traverseFieldArgs = void 0;
3
+ exports.traverseFieldArgs = traverseFieldArgs;
4
4
  function traverseFieldArgs(fields, cb) {
5
5
  const values = Object.values(fields);
6
6
  for (let x of values) {
@@ -15,4 +15,3 @@ function traverseFieldArgs(fields, cb) {
15
15
  traverseFieldArgs(fields, cb);
16
16
  }
17
17
  }
18
- exports.traverseFieldArgs = traverseFieldArgs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@technicity/data-service-generator",
3
- "version": "0.14.5",
3
+ "version": "0.16.0",
4
4
  "main": "./dist/index.js",
5
5
  "files": [
6
6
  "dist"
@@ -47,7 +47,7 @@
47
47
  "jest": "^29.4.3",
48
48
  "sinon": "12.0.1",
49
49
  "testcontainers": "^9.1.3",
50
- "typescript": "4.6.4"
50
+ "typescript": "5.5.2"
51
51
  },
52
52
  "resolutions": {
53
53
  "xml2js": "0.5.0",